【发布时间】:2016-04-02 00:14:19
【问题描述】:
考虑以下程序:
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 中也可以正常编译。那么,在上面的程序中发生了什么?
【问题讨论】:
-
虽然我理解这是一个好问题,但只是问
What C & C++ standard says about this?并不好。您是否尝试研究标准?你不明白哪一部分?你发现有什么不同吗?你的研究工作在哪里?希望我被理解。 :)
标签: c++ c arrays pointers constants