tags:

views:

209

answers:

3

Why when working with two dimensional arrays only second dimension is important for a compiler? Just can't get my head around that. Thanks

+5  A: 

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.

Milan Babuškov
Could you please give an example? How is it that if I have a[3][4] compiler needs just a[][4]? I can't understand this. Really.
There is nothing we can do
peachykeen
@peachykeen: this is somewhat misleading. The dimensions are needed for calculating the address of an array element. The first dimension is not needed, however, since it is not required for address calculation (the upper bound is irrelevant).
Paul R
"info to know how to lay things out in memory"Perhaps I didn't say it clearly, but I think we mean the same general thing. ;)
peachykeen
+1  A: 

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.

dmckee
+4  A: 

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.

Paul R