加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在多维和单维阵列之间进行投射

发布时间:2020-12-16 09:23:14 所属栏目:百科 来源:网络整理
导读:这是从 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* ar
这是从 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标准还指出一个数组由连续分配的元素组成,这消除了使用指针和填充做任何奇怪的事情的可能性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读