It is well known that a 2D array is an array of arrays, and that it is required by standard to be a contiguously allocated nonempty set of objects (6.2.5 Types §20) - object being a 1D array here.
It is also well known that for all common implementations the following equality is true for T arr2d[X][Y]
where T is a type and X and Y integral constants:
(char *) &arr2d[i][j] == (char *) &arr2d[0][0] + i * Y * sizeof(T) + j * sizeof(T)
The above let think that it could be allowed to alias a 2D array and an 1D array of same size, or even another 2D array of same total size:
For example the following program compiles and runs with no warnings, and gives expected output:
#include <stdio.h>
int main() {
int i, j, k=0;
int arr2d[3][4]; // array of 3 array of 4 ints
int *arr1 = &arr2d[0][0]; // pointer to first element of an array of 12 ints (1)
int (*arrx)[3] = (int(*)[3]) arr1; //pointer to first row of an array of arrays of 3 ints
//(2)
for (i=0; i<12; i++) arr1[i] = k++; // (3)
for (i=0; i<3; i++) {
for (j=0; j<4; j++) {
printf("%3d", arr2d[i][j]);
}
putc('
', stdout);
}
for (i=0; i<4; i++) {
for (j=0; j<3; j++) {
printf("%3d", arrx[i][j]);
}
putc('
', stdout);
}
return 0;
}
But:
- line (1) and (3) alias a 2D array 3x4 to a 1D array 12
- line (2) alias a 2D array 3x4 to a 2D array 4x3 (via a pointer to int)
My questions are:
- are (1) and (3) valid according to the C standard?
- if yes, is (2) valid?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…