以下代码片段(正确)在C中发出警告,在C++中发出错误(分别使用gcc和g ++,使用版本3.4.5和4.2.1进行测试; MSVC似乎并不关心):
char **a;
const char** b = a;
Run Code Online (Sandbox Code Playgroud)
我能理解并接受这个.
这个问题的C++解决方案是将b更改为const char*const*,它不允许重新分配指针并阻止你绕过const-correctness(C++ FAQ).
char **a;
const char* const* b = a;
Run Code Online (Sandbox Code Playgroud)
但是,在纯C中,更正后的版本(使用const char*const*)仍会发出警告,我不明白为什么.有没有办法绕过这个而不使用演员?
澄清:
1)为什么这会在C中产生警告?它应该完全是const安全的,并且C++编译器似乎认识到它.
2)在说(并让编译器强制执行)我不会修改它指向的字符时,接受这个char**作为参数的正确方法是什么?例如,如果我想写一个函数:
void f(const char* const* in) {
// Only reads the data from in, does not write to it
}
Run Code Online (Sandbox Code Playgroud)
我想在char**上调用它,参数的正确类型是什么?
编辑:感谢那些做出回应的人,特别是那些提出问题和/或跟进我的回复的人.
我已经接受了这样一个答案,即如果没有演员阵容,我想做的事情是无法完成的,无论是否应该这样做.
指向非const数据的指针可以隐式转换为指向相同类型的const数据的指针:
int *x = NULL;
int const *y = x;
Run Code Online (Sandbox Code Playgroud)
添加额外的const限定符以匹配额外的间接寻址应该在逻辑上以相同的方式工作:
int * *x = NULL;
int *const *y = x; /* okay */
int const *const *z = y; /* warning */
Run Code Online (Sandbox Code Playgroud)
-Wall但是,使用标志对GCC或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 */
^ ~
Run Code Online (Sandbox Code Playgroud)
为什么添加额外的const限定符"在嵌套指针类型中丢弃限定符"?