Rishab Shinghal
Rishab Shinghal

Reputation: 591

Why is it allowed to omit the first dimension, but not the other dimensions when declaring a multi-dimensional array?

Why it is not necessary to mention first dimension of multidimensional array and necessary to mention other dimensions:

int A[][][2]={{{1,2},{3,4}},{{4,5},{5,6}}}; // error 
int A[][2][2]={{{1,2},{3,4}},{{4,5},{5,6}}}; // OK 

I am not able to understand the concept or logic behind this.

Upvotes: 11

Views: 2626

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 148890

Because when using a multidimensional array, computing the actual index uses all dimension sizes except the first. For example for a 3D array declared as int arr[3][4][5];, arr[i][j][k] is by definition *(&(arr[0][0][0]) + k + 5 *(j + 4 * i))

So when the first dimension can be deduced from the context initialization, or may be ignored (when getting a parameter in a funtion) it can be omitted.

Examples:

int arr[][2] = { 1,2,3,4 };

void setArr(void *container, int arr[][4]);

Upvotes: 7

haccks
haccks

Reputation: 106012

It is necessary to mention both dimensions of 2D arrays except when it is in function's parameter or if an initializer is present then first dimension can be omitted.

When used as a parameter in a function, for example,

int 2D_arr[m][n]   

converted to

int (*2D_arr)[n]  

Therefore, first dimension can be omitted. But, second dimension must be there to tell the compiler that the pointer 2D_arr is a pointer to an array of n ints.

In second case, when initializer is present

int A[][2][2]={{{1,2},{3,4}},{{4,5},{5,6}}};    

the compiler uses the length of the initializer to calculate the first dimension only. The rest of the dimension must be explicitly specified at the time of declaration.

Upvotes: 8

dspfnder
dspfnder

Reputation: 1123

If you declare a 2D array in a static way...

int arr[3][4];

... then its two dimensions are obvious.

If you declare a 2D array in a dynamic way, or as a pointer to pointers...

int r = 3, c = 4;
int** arr = new int*[r];
for (int i = 0; i < r; i++) {
    arr[i] = new int[c];
}

... it looks as if only one dimension is mentioned during allocation but that's because first you allocate the rows and then each column. When you get or set an element, you specify both dimensions as usual...

num = arr[1][2];
arr[1][2] = num;

Upvotes: 1

Related Questions