简体   繁体   English

C中的char * vs const char *

[英]char* vs const char* in C

char* str ="Hello";

In the above code the literal "Hello" is stored ... in the DATA segment and it is read-only. 在上面的代码中,文字“ Hello”存储在DATA段中,并且是只读的。 So isn't it better to always declare it: 所以总是声明它不是更好:

const char* str = "Hello";

to avoid improper code such as: 避免使用不正确的代码,例如:

*(str+1) = 't';

"Hello" is stored ... in the DATA segment “ Hello”存储在DATA段中

"DATA" or .data would refer to the segment where initialized read/write variables with static storage duration go. “ DATA”或.data指的是带有静态存储持续时间的初始化读/写变量所在的段。 String literals are not stored there, but more likely in something called .rodata , or possibly in .text along with the code. 字符串文字不存储在此处,而是更有可能存储在名为.rodata ,也可能与代码一起存储在.text See String literals: Where do they go? 请参见字符串文字:它们去哪里了?

So isn't it better to always declare it: const char* str = "Hello"; 所以总是声明它不是更好: const char* str = "Hello";

Yes, you should always const qualify pointers to string literals. 是的,您应该始终const限定指向字符串文字的指针。 This is universally considered best practice in C (and mandatory in C++). 普遍认为这是C语言中的最佳做法(在C ++中是强制性的)。

Yes, it is better to declare pointers to string literals as const char * . 是的,最好将指向字符串文字的指针声明为const char * The name "literal" very strongly suggests that this is something that is supposed to be immutable. “文字”这个名字非常有力地暗示这是不可变的。 Unfortunately, C treats string literals as arrays of char , not const char , and unlike numeric literals storage for the string literal must be allocated from somewhere. 不幸的是,C将字符串文字视为char数组,而不是const char ,并且与数字文字不同,必须从某个地方分配字符串文字的存储空间。 It is not guaranteed that this storage will be taken from a read-only segment like .rodata - I've worked with implementations in the past where string literals were writable. 无法保证此存储空间将取自.rodata类的只读段-过去,我一直在处理可写字符串文字的实现。

The behavior on attempting to modify the contents of a string literal is undefined - the language places no requirement on the compiler or the runtime environment to handle the situation in any particular way. 尝试修改字符串文字内容的行为是未定义的 -该语言对编译器或运行时环境没有要求以任何特定方式处理这种情况。 You may get a runtime error, or the string may be left unchanged, or the string may be modified, any something entirely different could happen. 可能会遇到运行时错误,或者字符串可能保持不变,或者字符串可能被修改,可能会发生完全不同的事情。

So by declaring the pointer as const char * , you're at least making it harder to accidentally modify a literal through that pointer. 因此,通过将指针声明为const char * ,至少可以使通过该指针意外修改文字变得更加困难。 Just remember that const doesn't mean "put this thing in read-only memory" - it only means "issue a diagnostic if someone tries to modify this thing". 只需记住const 并不意味着“将其放入只读存储器中”,而仅意味着“如果有人尝试修改此事物,则发出诊断信息”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM