在多维和单维阵列之间进行投射操作,应该如何实现?

2026-04-16 18:202阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计393个文字,预计阅读时间需要2分钟。

在多维和单维阵列之间进行投射操作,应该如何实现?

这是从我的上一个问题的这个回答开始的。是否保证编译器将数组[4][4]与数组[16]视为相同?例如,下面对于api_func()的任意一次调用都是安全的吗?

cppvoid api_func(const double matrix[4][4]) { /*...*/ }

这是从 this answer to a previous question of mine开始的.
是否保证编译器将数组[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 n elements is n times 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标准还指出一个数组由连续分配的元素组成,这消除了使用指针和填充做任何奇怪的事情的可能性.

本文共计393个文字,预计阅读时间需要2分钟。

在多维和单维阵列之间进行投射操作,应该如何实现?

这是从我的上一个问题的这个回答开始的。是否保证编译器将数组[4][4]与数组[16]视为相同?例如,下面对于api_func()的任意一次调用都是安全的吗?

cppvoid api_func(const double matrix[4][4]) { /*...*/ }

这是从 this answer to a previous question of mine开始的.
是否保证编译器将数组[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 n elements is n times 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标准还指出一个数组由连续分配的元素组成,这消除了使用指针和填充做任何奇怪的事情的可能性.