Home>Article>Backend Development> What is the order in which two-dimensional array elements are stored in memory in C language?

What is the order in which two-dimensional array elements are stored in memory in C language?

烟雨青岚
烟雨青岚 Original
2020-06-28 14:54:07 10003browse

In the C language, two-dimensional array elements are stored in rows in memory. Two-dimensional array A[m][n], which is a two-dimensional array with m rows and n columns; assuming a[p][q] is the first element of A, it can be stored according to "row priority" or "Column major" storage is used to calculate the address of element a[i][j].

What is the order in which two-dimensional array elements are stored in memory in C language?

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-major order", the address is calculated as:

LOC(a[i][j]) = LOC(a[p][q]) ( (j − q) * m (i − p)) * t;

The minimum number of units required to store this array is (m-p 1) * (n-q 1) * t bytes.

What is the order in which two-dimensional array elements are stored in memory in C language?

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]. This marking will be better. Because sizeof The (date) result is 4 and 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 Language"

The above is the detailed content of What is the order in which two-dimensional array elements are stored in memory in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn