gpt4 book ai didi

c++ - 为什么警告要实现指向字符串的指针数组?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:09 26 4
gpt4 key购买 nike

我正在尝试使用指针实现一个字符串数组。以下是我的代码。

#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"abcd",
"efgh",
"ijkl",
"mnop",
};
int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}

我在运行它时收到警告。以下是警告:

C:\workspace>g++ test_pointer_string_arr.c -o tpsa.exe
test_pointer_string_arr.c: In function 'int main()':
test_pointer_string_arr.c:12:4: warning: deprecated conversion from string const
ant to 'char*' [-Wwrite-strings]
};
^
test_pointer_string_arr.c:12:4: warning: deprecated conversion from string const
ant to 'char*' [-Wwrite-strings]
test_pointer_string_arr.c:12:4: warning: deprecated conversion from string const
ant to 'char*' [-Wwrite-strings]
test_pointer_string_arr.c:12:4: warning: deprecated conversion from string const
ant to 'char*' [-Wwrite-strings]

问题是什么?

最佳答案

C 中的字符串文字是不可变的。任何更改字符串文字内容的尝试都会调用 undefined behavior .

根据定义,字符串具有 char [] 类型,因此,通过将 string literal 分配给 char * 不会 阻止您编写静默调用 UB 的代码。

关于gcc选项,-Wwrite-strings

-Wwrite-strings

When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer produces a warning. These warnings help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make -Wall request these warnings.

所以,你需要写

 const char *names[] = {
"abcd",
"efgh",
"ijkl",
"mnop",
};

同样如此。

如前所述,大多数时候,可能不值得。

关于c++ - 为什么警告要实现指向字符串的指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37135425/

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