gpt4 book ai didi

c - 为什么 char *s = "string"在不是 const 时不显示错误或警告

转载 作者:太空狗 更新时间:2023-10-29 15:52:06 24 4
gpt4 key购买 nike

下一行

char *s = "string";

即使使用 -Wall 也不会在 gcc 上抛出任何警告/错误。

AFAIK,指针 s 直接指向 .rodata 的某个部分,使其成为指向 const char.

那么,为什么指针不提示并期待:

const char *s = "string";

:不管怎样,使用后者是更好的做法吗?

最佳答案

来自 gcc 编译选项:

-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.

所以显然您需要明确允许 -Wwrite-strings,而 Wall 不包含它。

关于c - 为什么 char *s = "string"在不是 const 时不显示错误或警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28276346/

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