I wrote the following code In c just to check whether the code would break or not:
int main(void)
{
int A [5] [2] [3];
printf("%d\n\n", A[6]);
printf("%d\n\n", &A[6][0][0]);
system("pause");
}
Now, the code does not break which was something I was not expecting. When we declare a multidimensional array: int A [5][2][3], doesn’t that conceptually mean that A in its first level is a one-dimensional array of 5 elements ( 0 – 4 ) and every element of that array is itself a one-dimensional array of 2 elements and every element of that array is a one-dimensional array of 3 elements? If that concept is correct, how can
A[6][0][0] even exist – since in the first level we only have 5 elements ( 0 based ) .
Any help, would be greatly appreciated.
You are accessing a position outside the array, there is no
A[6]. That’s undefined behavior, and anything could happen.Note that
A[5]is a well defined location (past the end of the array), so getting a pointer to it is legal but trying to access that pointer is not. However, getting a pointer toA[6]or any other greater index is completely undefined.