Initializing a 2D array like a 1D array

后端 未结 3 1108

I have initialized a 2D array like a 1D array:

int a[2][3] = {1,2,3,4,5} 

How are the values stored in this array?

3条回答
  •  礼貌的吻别
    2021-01-06 01:50

    In C, 1D arrays are stored in a single linear buffer in memory in what is called "row major" order. Row major means that the last index varies fastest as you go from element to element. Column major would mean that the first index varies fastest, as it does in MATLAB, for example.

    The array you declared is only 2D in the sense that the compiler helps you out by computing the linear address of the elements for you. The address of an element in a 1D array is computed linear[x] = linear + x. Similarly, for your 2D array, a[y][x] = a + 3 * y + x. In general, a[y][x] = a + num_cols * y + x.

    You can initialize the array as a single vector of elements, which will first fill the first row, then the second, and so on. Since you have two rows of three elements each, the first row becomes 1, 2, 3 and the second row becomes 4, 5, 0.

    Indexing past the end of a row is perfectly valid, as far as the compiler is concerned at least. In the example you give, a[0][3] is accessing the fourth element of the first row in an array that is three elements wide. With wrap-around, you can see that this is just the first element of the second row, which is more explicitly stated as a[1][0].

    Because of the lax index checking, you can completely omit the first index in any array as long as you provide an initializer. The formula to compute the linear address does not depend on the first index (because it is row major), and the total number of elements is specified by the initializer itself. A 1D example is int linear[] = {1, 2, 3};.

    Keep in mind that the name of the array also refers to the pointer to its first element. These are two different things that can be accessed by the same name.

提交回复
热议问题