gpt4 book ai didi

数组的 C 数组 : why do I need to cast TO const here?

转载 作者:行者123 更新时间:2023-12-02 04:47:53 24 4
gpt4 key购买 nike

为什么我需要将此代码中的 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 a const char ** pointer is somewhat obscure. Given that the const qualifier exists at all, the compiler would like to help you keep your promises not to modify const values. That's why you can assign a char * to a const
char *
, but not the other way around: it's clearly safe to "add" 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 来阻止你做,修改 指向的 char指向指向 const char 的指针,因此第 3 行不允许,并且您不能将 char ** 分配给 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com