F
Frederick Gotham
In another thread recently, there was discussed the accessing of array
indices which were out of bounds. Obviously, the following code is bogus:
int arr[5];
arr[9] = 4;
Take the following snippet however:
int arr[2][5];
arr[0][9] = 4;
The definition of "arr" results in a chunk of memory of size: sizeof(int)*5
*2
Therefore, I would have thought that there was nothing wrong with the
accessing of the 10th element (if we look at it as a one-dimensional array
of int's). I've been told, however, that the behaviour is undefined.
This seems strange to me, especially given that we should be able to access
memory however we like in C. For example, look at the free reign we have
with the following:
int *const p = malloc(128 * sizeof*p);
p[56] = 4;
double *const pd = (double*)p;
pd[0] = 56.334;
What about the following snippet; is the behaviour undefined?
int (*p)[5][6] = malloc(5*6*sizeof*p);
(*p)[0][8] = 7;
Can the second snippet be remedied by simply adding a pointer? e.g.:
int arr[2][5];
/* arr[9] = 4; */
int *const p = (int*)&**arr;
p[9] = 4;
indices which were out of bounds. Obviously, the following code is bogus:
int arr[5];
arr[9] = 4;
Take the following snippet however:
int arr[2][5];
arr[0][9] = 4;
The definition of "arr" results in a chunk of memory of size: sizeof(int)*5
*2
Therefore, I would have thought that there was nothing wrong with the
accessing of the 10th element (if we look at it as a one-dimensional array
of int's). I've been told, however, that the behaviour is undefined.
This seems strange to me, especially given that we should be able to access
memory however we like in C. For example, look at the free reign we have
with the following:
int *const p = malloc(128 * sizeof*p);
p[56] = 4;
double *const pd = (double*)p;
pd[0] = 56.334;
What about the following snippet; is the behaviour undefined?
int (*p)[5][6] = malloc(5*6*sizeof*p);
(*p)[0][8] = 7;
Can the second snippet be remedied by simply adding a pointer? e.g.:
int arr[2][5];
/* arr[9] = 4; */
int *const p = (int*)&**arr;
p[9] = 4;