指向非常量数据的指针可以隐式转换为指向相同类型的常量数据的指针:
int *x = NULL;
int const *y = x;
在逻辑上,添加其他const限定符以匹配其他间接寻址应以相同的方式进行:
int * *x = NULL;
int *const *y = x; /* okay */
int const *const *z = y; /* warning */
但是,使用GCC或带有
-Wall
标志的Clang进行编译会导致以下警告:test.c:4:23: warning: initializing 'int const *const *' with an expression of type
'int *const *' discards qualifiers in nested pointer types
int const *const *z = y; /* warning */
^ ~
为什么要添加附加的
const
限定词“丢弃嵌套指针类型中的限定词”?
最佳答案
const
只能添加一个级别的原因很细微,并由Question 11.10 in the comp.lang.c FAQ解释。
简要地,请考虑与您的示例紧密相关的示例:
const int i;
int *p;
int const **z = &p;
*z = &i;
/* Now p points to i */
C通过仅允许分配在第一个指向级别上丢弃限定符来避免此问题(因此,此处不允许分配给
z
)。您的确切示例不会遇到此问题,因为
const
第二级意味着无论如何都不允许分配给*z
。在这种确切的情况下,C ++允许这样做,但是C的简单规则无法区分您的情况和上述示例。
关于c - C中的双指针const正确性警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080343/