问题描述
考虑以下程序:
int main()
{
int array[9];
const int (*p2)[9] = &array;
}
它在 C++ 中编译得很好(参见现场演示 这里)但在 C 中编译失败.默认情况下,GCC 给出以下警告.(查看现场演示此处).
It compiles fine in C++ (See live demo here) but fails in compilation in C. By default GCC gives following warnings. (See live demo 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
选项:
But If I use -pedantic-errors
option:
gcc -Os -s -Wall -std=c11 -pedantic-errors -o constptr constptr.c
它给了我以下编译器错误
it gives me following compiler error
constptr.c:4:26: error: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]
为什么它在 C 中编译失败,而在 C++ 中却没有?什么 C &C++ 标准对此有何规定?
Why it fails in compilation in C but not in C++? What C & C++ standard says about this?
如果我在数组声明语句中使用 const 限定符,它也可以在 C 中正常编译.那么,在上面的程序中发生了什么?
If I use const qualifier in array declaration statement it compiles fine in C also. So, what is happening here in above program?
推荐答案
在 GNU C 中,指向带有限定符的数组的指针的工作方式类似于指向其他限定类型的指针.例如,int (*)[5]
类型的值可用于初始化 const int (*)[5]
类型的变量.这些类型在 ISO C 中是不兼容的,因为 const
限定符正式附加到数组的元素类型而不是数组本身.
C 标准说(部分:§6.7.3/9):
C standard says that (section: §6.7.3/9):
如果数组类型的规范包含任何类型限定符,则元素类型是如此限定的,不是数组类型.[...]
现在看看 C++ 标准(第 3.9.3/5 节):
Now look at the C++ standard (section § 3.9.3/5):
[...] 应用于数组类型的 Cv 限定符附加到底层元素类型,因此符号cv T
",其中 T
是一个数组类型,指的是一个数组,其元素是如此限定的.元素为 cv 限定的数组类型也被认为具有与其元素相同的 cv 限定.[ 示例:
typedef char CA[5];
typedef const char CC;
CC arr1[5] = { 0 };
const CA arr2 = { 0 };
arr1
和 arr2
的类型都是5 const char 的数组", 并且数组类型被认为是是常量限定的.—结束示例]
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]的指针到指向int
指针的赋值/em>.这与将 int *
分配给 const int *
不同,其中 const
直接应用于指针指向的 对象类型.const int(*)[9]
不是这种情况,在 C 中,const
应用于数组对象的元素而不是指针指向的对象到.这使得上述初始化不兼容.
is assignment of type pointer to array[9] of int
to pointer to array[9] of const int
. This is not similar to assigning int *
to a const int *
where const
is applied directly to the object type the pointer points to. This is not the case with const int(*)[9]
where, in C, const
is applied to the elements of the array object instead of the object the pointer points to. This makes the above initialization incompatible.
此规则在 C++ 中有所更改.由于const
应用于数组对象本身,因此赋值是在相同类型的指针之间,指向int
的const array[9] 而不是类型指向int
的数组[9]的指针和指向int
的数组[9]的指针.
This rule is changed in C++. As const
is applied to array object itself, the assignment is between same types pointer to const array[9] of int
instead of type pointer to array[9] of int
and pointer to array[9] of const int
.
这篇关于C&中带有const限定符的数组指针C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!