Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is only the second array dimension important?

Tags:

c++

arrays

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

like image 409
There is nothing we can do Avatar asked Apr 01 '10 16:04

There is nothing we can do


2 Answers

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.

like image 86
Milan Babuškov Avatar answered Sep 22 '22 19:09

Milan Babuškov


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.

like image 23
Paul R Avatar answered Sep 23 '22 19:09

Paul R