char* str ="Hello";
在上面的代码中,文字“Hello”存储在……数据段中,并且它是只读的。 所以总是声明它不是更好吗:
const char* str = "Hello";
避免不正确的代码,例如:
*(str+1) = 't';
最佳答案
"Hello" is stored ... in the DATA segment
“DATA”或.data
指的是具有静态存储持续时间的初始化读/写变量所在的段。字符串文字不存储在那里,但更有可能存储在名为 .rodata
的东西中,或者可能与代码一起存储在 .text
中。
参见 String literals: Where do they go?
So isn't it better to always declare it:
const char* str = "Hello";
是的,您应该始终const
限定指向字符串文字的指针。这在 C 中被普遍认为是最佳实践(并且在 C++ 中是强制性的)。
关于C 中的 char* 与 const char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818160/