Reputation: 77
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.
Upvotes: 0
Views: 114
Reputation: 81349
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 to A[6]
or any other greater index is completely undefined.
Upvotes: 5
Reputation: 59617
C doesn't do array bounds checking. For int A[4]
, think of A[5]
as like pointer arithmetic: *(A + 5)
.
Even if A
has only been declared with 5 elements (0-4), C will allow you to reference memory outside the declared bounds of your array, using A
.
The result of this access is undefined. If you read A[5]
, you might get garbage; if you write A[5]
, i.e. A[5] = 13
, you may corrupt another allocated block of memory.
The wiki article is a pretty good start for understanding this, but I recommend that you pick up a copy of K&R, read it, and do all the exercises.
Upvotes: 0