gpt4 book ai didi

c++ - C 和 C++ 中带有 const 限定符的数组指针

转载 作者:行者123 更新时间:2023-11-30 16:36:58 24 4
gpt4 key购买 nike

考虑以下程序:

int main()
{
int array[9];
const int (*p2)[9] = &array;
}

它在 C++ 中编译良好(请参见实时演示 here ),但在 C 中编译失败。默认情况下,GCC 会给出以下警告。 (请参阅现场演示 here )。

prog.c: In function 'main':
prog.c:4:26: warning: initialization from incompatible pointer type [enabled by default]
const int (*p2)[9] = &array;

但是如果我使用 -pedantic-errors 选项:

gcc -Os -s -Wall -std=c11 -pedantic-errors -o constptr constptr.c

它给了我以下编译器错误

constptr.c:4:26: error: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]

为什么C编译失败而C++编译失败? C 和 C++ 标准对此有何规定?

如果我在数组声明语句中使用 const 限定符,它在 C 中也可以正常编译。那么,上面的程序中发生了什么?

最佳答案

GCC-gnu

In GNU C, pointers to arrays with qualifiers work similar to pointers to other qualified types. For example, a value of type int (*)[5] can be used to initialize a variable of type const int (*)[5]. These types are incompatible in ISO C because the const qualifier is formally attached to the element type of the array and not the array itself.

C 标准规定(第 6.7.3/9 节):

If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type.[...]

现在看看 C++ 标准(第 § 3.9.3/5 节):

[...] Cv-qualifiers applied to an array type attach to the underlying element type, so the notation “cv T,” where T is an array type, refers to an array whose elements are so-qualified. An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements. [ Example:

 typedef char CA[5];
typedef const char CC;
CC arr1[5] = { 0 };
const CA arr2 = { 0 };

The type of both arr1 and arr2 is “array of 5 const char,” and the array type is considered to be const- qualified. —endexample]

因此,初始化

const int (*p2)[9] = &array;  

是指向int的数组[9]的指针类型的赋值指向 const int 的数组 [9] 的指针。这与分配 int * 不同。到 const int *哪里const直接应用于指针指向的对象类型const int(*)[9] 的情况并非如此。其中,在 C 中,const应用于数组对象的元素而不是指针指向的对象。这使得上述初始化不兼容。

此规则在 C++ 中已更改。如const应用于数组对象本身,赋值是在指向 int 的 const array[9] 的相同类型指针之间进行的 而不是类型指向int 的数组[9] 的指针 指向 const int 的数组 [9] 的指针

关于c++ - C 和 C++ 中带有 const 限定符的数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48209814/

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