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;}