- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么我需要将此代码中的 print_args
调用更改为 print_args(argc, (const char**)argv)
以使其编译?
#include <stdio.h>
void print_args(int argc, const char *argv[]) {
for (int i = 0; i < argc; ++ i) {
puts(argv[i]);
}
}
int main(int argc, char *argv[]) {
print_args(argc, argv);
return 0;
}
当我用 gcc 编译它时,我得到这个错误:
$ gcc -Werror -std=c99 -g const.c -o const
const.c: In function ‘main’:
const.c:10:2: error: passing argument 2 of ‘print_args’ from incompatible pointer type [-Werror]
const.c:3:6: note: expected ‘const char **’ but argument is of type ‘char **’
cc1: all warnings being treated as errors
(请注意,这只是一个简化的示例代码来说明问题。)
最佳答案
comp.lang.c 常见问题 has a question on this , 总结:
The reason that you cannot assign a
char **
value to aconst char **
pointer is somewhat obscure. Given that theconst
qualifier exists at all, the compiler would like to help you keep your promises not to modifyconst
values. That's why you can assign achar *
to aconst
, but not the other way around: it's clearly safe to "add"
char *const
-ness to a simple pointer, but it would be dangerous to take it away...In C, if you must assign or pass pointers which have qualifier mismatches at other than the first level of indirection, you must use explicit casts
这是它给出的示例,其中第 3 行应该给出警告:
const char c = 'x'; /* 1 */
char *p1; /* 2 */
const char **p2 = &p1; /* 3 */
*p2 = &c; /* 4 */
*p1 = 'X'; /* 5 */
第 1 行和第 2 行显然没问题。在第 4 行,&c
的类型为 pointer to const char
,因为 char **
的类型为 pointer to pointer to const char
,则*p2
也是pointer to const char
类型,所以语句没问题。第 5 行也很好,因为 p1
是类型 pointer to char
,所以你可以修改它指向的内容。
所以如果第 3 行没问题,那么你最终会完全按照你期望的 const
来阻止你做,修改 指向的
的指针,因此第 3 行不允许,并且您不能将 char
指向指向 const charchar **
分配给 const char **
没有强制转换。
请注意,强制转换只是隐藏问题,并不能解决问题。如果您添加了转换,上面的第 3 行将起作用,并且您将能够间接修改明显的 const char
。虽然这并不总是正确的,但这是一个很好的例子,表明屈服于明显需要在 C 中进行强制转换通常只是一个错误。
请注意,在 C++ 中,您可以声明您的函数参数 const char * const * argv
并且它可以在没有转换的情况下工作,并防止间接修改。
关于数组的 C 数组 : why do I need to cast TO const here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440658/
我是一名优秀的程序员,十分优秀!