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

标签 c pointers constants

下一行

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/

相关文章:

c - 具有循环缓冲区的多生产者单消费者

c - 为什么使用此 C 代码会出现段错误?

java - 使用非静态公共(public)最终变量公开实例常量

C++ 带有自定义删除器错误的唯一指针

c++ - 如何将 char 数组定义为常量?

c - 在 ANSI C 中,const 值是全局的?

C打开并读取txt文件

检查 char* 中的空终止字符

c++ - 在 VS 中从 C 中的 long 转换为 C++ 中的 long 时出现意外输出?

c - 在 C 中使用指针访问二维数组