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.
The accepted answer to this question explains it pretty well. Think of an n-dimensional array as a simple array with n-1 dimensional elements. Just as you don't pass the size of a 1 dimensional array, you don't pass the size of the first dimension of an n dimensional array.
When declaring a two-dimensional array as a formal parameter, what can you omit? The size of the first dimension but not the second. When a two-dimensional array is passed as an actual parameter, what must match? The number of columns of the actual and formal arrays.
You actually need to specify all dimensions besides the first one. The reason is that the compiler won't know how much memory to allocate otherwise. It also won't know the size of the first one to skip over if you want the second index.
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With