简体   繁体   English

为什么我不能修改 c 中的字符串文字?

[英]Why can I not modify a string literal in c?

I am trying to understand the reason behind not being able to modify a string literal in C.我试图理解无法在 C 中修改字符串文字的原因。

Why is the following illegal in C?为什么以下在 C 中是非法的?

char* p = "abc";
*p = 'd';

From the C89 Rationale, 3.1.4 String literals :C89 基本原理,3.1.4 字符串文字

String literals are specified to be unmodifiable.字符串文字被指定为不可修改。 This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and perform certain optimizations.该规范允许实现共享具有相同文本的字符串副本,将字符串文字放置在只读 memory 中,并执行某些优化。 However, string literals do not have the type array of const char, in order to avoid the problems of pointer type checking, particularly with library functions, since assigning a pointer to const char to a plain pointer to char is not valid.但是,字符串文字没有 const char 的类型数组,为了避免指针类型检查的问题,特别是对于库函数,因为将指向 const char 的指针分配给指向 char 的普通指针是无效的。 Those members of the Committee who insisted that string literals should be modifiable were content to have this practice designated a common extension (see F.5.5).那些坚持字符串文字应该是可修改的委员会成员满足于将这种做法指定为一个公共扩展(参见 F.5.5)。

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

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