This came up from this answer to a previous question of mine. Is it guaranteed for the compiler to treat array[4][4] the same as array[16]?
For instance, would either of the below calls to api_func() be safe?
void api_func(const double matrix[4][4]); // ... { typedef double Matrix[4][4]; double* array1 = new double[16]; double array2[16]; // ... api_func(reinterpret_cast<Matrix&>(array1)); api_func(reinterpret_cast<Matrix&>(array2)); }
From the C++ standard, referring to the
sizeofoperator:From this, I’d say that
double[4][4]anddouble[16]would have to have the same underlying representation.I.e., given
and
then we have
I think a standards-compliant compiler would have to implement these the same, and I think that this isn’t something that a compiler would accidentally break. The standard way of implementing multi-dimensional arrays works as expected. Breaking the standard would require extra work, for likely no benefit.
The C++ standard also states that an array consists of contiguously-allocated elements, which eliminates the possibility of doing anything strange using pointers and padding.