Why is only the second array dimension important?
Why when working with two dimensional 开发者_如何学Goarrays only second dimension is important for a compiler? Just can't get my head around that. Thanks
Because compiler needs to figure out how to access the data from memory. The first dimension is not important because compiler can count the number of items when all other sizes are given.
Examples:
int a1[] = { 1, 2, 3, 4 }
compiler knows to allocate space for 4 integers. Now, with this:
int a2[][] = { 1, 2, 3, 4, 5, 6} }
compiler cannot decide whether it should be a2[1][6] or a2[2][3] or a2[3][2] or a2[6][1]. Once you tell it the second dimension, it can calculate the first one.
For example, trying to access element a2[1][0] would yield different values depending on the declaration. You could get 2, 3, 4 or even invalid position.
It's not the "second dimension" (except when you only have 2 dimensions) - it's "all but the first dimension". So you can have int a[][2][3][4]
for example. Without these dimensions it would not be possible to calculate the address of an element.
Sit down and figure out how to find the memory position of a[i][j]
given the starting position of the array.
Note that c arrays are laid out like this a[0][0]
a[0][1]
a[0][2]
... a[0][M]
a[1][0]
...
Side note: FORTRAN arrays are laid out differently: a[1][1]
a[2][1]
a[3][1]
... a[N][1]
a[1][2]
...
Notice how this would change which dimension is needed for finding memory positions.
精彩评论