Is a "reformatting" of a multidimensional array a pointer to an invalid array type permitted in C?

Consider the following declaration:

int a[M][N]; // M and N are known compile-time 

It would be legal to treat him as it was declared as:

 int a[N][M]; 

or even:

 int a[A][B]; // where A * B = M * N 

in C without breaking its rules (bad)?

I found that it can be executed without any throws:

 #include <stdio.h> void print_array(int a[][2], int n); int main(void) { int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; //int (*p1)[2] = a; // compile error int (*ptr_temp)[] = a; // pointer to array of incomplete type int (*p2)[2] = ptr_temp; // compiles without any warning print_array(p2, 3); } void print_array(int a[][2], int n) { for (int i = 0; i < n; i++) for (int j = 0; j < 2; j++) printf("a[%d][%d] = %d\n", i, j, a[i][j]); } 

Note that we cannot directly bind a pointer to p1 . However, the compiler does not complain when p2 assigned to ptr_temp , even if it seems potentially dangerous (it does not require any casting for this). Is it really sanitized? If so, why does this prohibit the first appointment?

+8
c c11
source share
1 answer

The behavior you see is related to how multidimensional arrays are handled in C.

Look at this question. Pointer address in multidimensional array C

+1
source share

All Articles