差异C和C之间的不完整的数组指针转换规则++ [英] Difference in incomplete array pointer conversion rules between C and C++

查看:285
本文介绍了差异C和C之间的不完整的数组指针转换规则++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译下面code。与 GCC G ++ G ++ 给出错误,而不是 GCC 。请注意,code从 INT(*)转换[4] INT(*)[] (这是指向完整的数组类型)。

When I compile the following code with gcc and g++, g++ gives error and not gcc. Note that the code converts from int (*)[4] to int (*)[] (which is pointer to incomplete array type).

int arr[4];
int (*p_arr)[] = &arr;

不完全数组类型?, C 语言允许这种转换。但是,为什么 C ++ 禁止这一点,并给出了误差错误:无法转换'INT(*)[4]'到'INT(*)[] 在分配。我知道C ++更加类型安全比C,但是这个任务实在是类型不安全的,因为指针的后来取消引用(如的sizeof(* p_arr))反正给出错误的 C 以及

As discussed in Incomplete array type?, C language allows this conversion. But why does C++ disallow this and gives the error error: cannot convert ‘int (*)[4]’ to ‘int (*)[]’ in assignment. I know C++ is more type-safe than C, but does this assignment is really type-unsafe, because the later dereference of the pointer (e.g. sizeof(*p_arr)) anyway gives error in C as well?

推荐答案

本身的转换是安全的,但要记住,在C相同的规则,允许这种转换也使得它在相反的方向。

The conversion by itself is safe, but keep in mind that the same rule in C that allows this conversion also allows it in the opposite direction.

int main() {
  int array[4] = {0};
  int (*ptr4)[4] = &array;
  int (*ptrN)[]  = ptr4;
  int (*ptr5)[5] = ptrN; /* oh dear */
}

这显然是不好的。 C ++已经删除了此规则,上面写着 INT [4] INT [] 是兼容的类型和$规则p $ ptty多少摆脱了兼容型的概念。

This is clearly bad. C++ has removed this rule, the rule that says int[4] and int[] are compatible types, and pretty much got rid of the concept of compatible type.

这是安全的正在考虑纳入C ++ 的未来版本。它们包括您的转换也是如此。

Some specific conversions that are safe are being considered for inclusion in a future version of C++. They include your conversion as well.

这篇关于差异C和C之间的不完整的数组指针转换规则++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆