这是从 this answer to a previous question of mine开始的. 是否保证编译器将数组[4] [4]与数组[16]相同? 例如,下面对api_func()的任何一个调用都是安全的吗? void api_func(const double matrix[4][4]);// ...{
是否保证编译器将数组[4] [4]与数组[16]相同?
例如,下面对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));
}
从C标准,参考sizeof运算符:
When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of
nelements isntimes the size of an element.
由此,我会说double [4] [4]和double [16]必须具有相同的底层表示.
即,给定
sizeof(double[4]) = 4*sizeof(double)
和
sizeof(double[4][4]) = 4*sizeof(double[4])
然后我们有
sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16])
我认为符合标准的编译器必须实现这些,我认为这不是编译器会意外破坏的.实现多维数组的标准方法按预期工作.打破标准需要额外的工作,可能没有任何好处.
C标准还指出一个数组由连续分配的元素组成,这消除了使用指针和填充做任何奇怪的事情的可能性.
