Casting between multi- and one-dimensional arrays

This triggered this answer to the previous question . Is array[4][4]the same guaranteed for the compiler as array[16]?

For example, will one of the following calls be safe api_func()?

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));
}
+3
source share
6 answers

From the C ++ standard, referring to the operator sizeof:

When applied to an array, the result is the total number of bytes in the array. This means that the size of the array of elements nis ntimes the size of the element.

From this, I would say that double[4][4]they double[16]should have the same basic idea.

Ie given

sizeof(double[4]) = 4*sizeof(double)

and

sizeof(double[4][4]) = 4*sizeof(double[4])

then we have

sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16])

, , , , , , . , . , .

++ , , - .

+3

, , .

, . [N] [M] , [M * ​​N].

+2

. , .

+1

@ :

( /), , : .

int x [3] [5], , 3, int 5. (§6.5.2.1). , .. , , 5-int . ( , 3 - , 5 ints x [1] [0] x [2] [0].)

+1

, Matrix [5] [5], , .

0

: ?

, , , . , double [m * n] , , , , , [] . - , my_matrix [3] [5], - , .

0

Source: https://habr.com/ru/post/1696793/


All Articles