gpt4 book ai didi

c++ - C和C++不完全数组指针转换规则的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:26 24 4
gpt4 key购买 nike

当我用 gccg++ 编译以下代码时,g++ 给出了错误,而不是 gcc。请注意,代码从 int (*)[4] 转换为 int (*)[](这是指向不完整数组类型的指针)。

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

Incomplete array type? 中所述, C 语言允许这种转换。但是为什么 C++ 不允许这样做并给出错误 error: cannot convert ‘int (*)[4]’ to ‘int (*)[]’ in assignment。我知道 C++ 比 C 更类型安全,但是这个赋值真的是类型不安全的,因为后来对指针的取消引用(例如 sizeof(*p_arr))无论如何都会在 中给出错误C 也是吗?

最佳答案

转换本身是安全的,但请记住,C 语言中允许这种转换的相同规则也允许相反方向的转换。

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

这显然很糟糕。 C++ 已经删除了这条规则,说 int[4]int[] 是兼容类型的规则,并且几乎摆脱了兼容类型的概念。

一些安全的特定转换are being considered for inclusion in a future version of C++ .它们也包括您的转化。

关于c++ - C和C++不完全数组指针转换规则的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33782518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com