Home > Article > Backend Development > What is the order in which two-dimensional arrays are stored in memory in C language?
In the C language, the storage order of two-dimensional arrays in memory is by row. The two-dimensional array A[m][n] is a two-dimensional array with m rows and n columns. Suppose a[p][q] is the first element of A, that is, the row subscripts of the two-dimensional array range from p to [m p], and the column subscripts range from q to [n q].
In the C language, two-dimensional array elements are stored row by row in memory.
Two-dimensional array A[m][n], which is a two-dimensional array with m rows and n columns. Let a[p][q] be the first element of A, that is, the row subscripts of the two-dimensional array are from p to m p, and the column subscripts are from q to n q. When stored in "row-major order", the element a[i The address of ][j] is calculated as:
LOC(a[i][j]) = LOC(a[p][q]) + ((i − p) * n + (j − q)) * t;
When stored in "column priority order", the address is calculated as:
LOC(a[i][j]) = LOC(a[p][q]) + ((j − q) * m + (i − p)) * t;
The minimum number of cells required to store the array is (m-p 1) * (n-q 1) * t
bytes.
Extended information:
C Dynamic two-dimensional array:
Take integer as an example, row is the number of rows, col is the number of columns
int **data;
//Storage pointer of two-dimensional array, pointer to pointer. The address of
date=x[0][0]
will be better marked this way. Because the result of sizeof(date)
is 4, it is impossible to store a two-dimensional array.
//以下实现如何申请内存 data = new int *[row]; for (int k = 0; k < row; k++) { data[k] = new int[col]; }
//赋值跟普通二维数组一样 例如 data[0][0] = 5; //将二维数组1行1列(C++中称为0行0列)赋值为5 //删除内存 for (int i = 0 ; i < row; ++i) { delete [] data[i]; //此处的[]不可省略 } delete [] data;
Recommended tutorial: "c video tutorial"
The above is the detailed content of What is the order in which two-dimensional arrays are stored in memory in C language?. For more information, please follow other related articles on the PHP Chinese website!