C/C ++ two-dimensional array as function parameter

Source: Internet
Author: User

There are two types of two-dimensional arrays:

Fixed dimensions

This type of array is stored on the stack continuously. Fixed multidimensional arrays of any dimension can be viewed as one-dimensional arrays and can be accessed in the form of a [I + J * n.

Int Ia [2] [2] = {2, 3, 4, 5}; // memory segment that is arranged consecutively when four elements exist // void F (int p [] [2], int row, int col) // This method requires you to know the size of the dimension except the first dimension, not flexible void F (int * P, int row, int col) // convert to a one-dimensional array to access {for (INT I = 0; I <row; I ++) {for (Int J = 0; j <Col; j ++) {cout <p [I * Col + J] <"" ;}} cout <Endl ;}

The following code is incorrect:

Int ** P = IA; // The type of IA is Char (*) [2], not ** int

This is because ** P points to the first address, because int ** P resolves the reference as an address pointer at a time, rather than the pointer to an array on the heap, so the second unreference will fail.

Dynamic Array

These arrays are stored on the stack. Only rows in a row are arranged consecutively, but not necessarily consecutively.

Int ** P = new int * [2]; // only the rows in each row are arranged consecutively and not necessarily consecutively for (INT I = 0; I <2; I ++) {P [I] = new int [2];} For (INT I = 0; I <2; I ++) {for (Int J = 0; j <2; j ++) {P [I] [J] = Ia [I] [J];}

The access to such Arrays can pass multidimensional pointers (two-dimensional ** P) and dimensions, which can be accessed directly using a [I] [J.

void f(int **p , int row, int col ){for(int i = 0; i < row; i++){for(int j =0 ;j < col; j++){cout<<p[i][j]<<" ";}}cout<<endl;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.