简体   繁体   English

将字符串文字分配给char []如何工作?

[英]How does assigning string literals to char[] work?

The C book I'm working through says that string literals are constants, but when I assign them to character arrays, individual characters can be assigned new values. 我正在研究的C书中说字符串文字是常量,但是当我将它们分配给字符数组时,可以为各个字符分配新值。 Are the string literals converted into something else during assignment? 字符串文字在赋值期间是否转换为其他形式? Are they not inherently constant? 它们不是天生不变的吗?

Reading through some other StackOverflow answers, some say that this should result in errors, so I can't figure out why it's working. 仔细阅读其他StackOverflow答案,有人说这应该会导致错误,因此我无法弄清楚它为什么起作用。

Running 运行

char string[12] = "hello world";
string[5] = '-';
printf(string);

Prints hello-world . 打印hello-world

Running 运行

"hello world"[5] = '-';

Results in an error error: assignment of read-only location '"hello world"[5]' during compilation. 导致错误error: assignment of read-only location '"hello world"[5]'在编译过程中error: assignment of read-only location '"hello world"[5]'

Typically, a string literal is stored in read-only memory; 通常,字符串文字存储在只读存储器中。 but, when you initialize a string literal to a character array, as in your first example, it gets copied into the character array, which is not in read-only memory. 但是,当您将字符串文字初始化为字符数组时,如第一个示例所示,它将被复制到字符数组中,该字符数组不在只读存储器中。 It is the character array that can be modified; 可以修改的字符数组; not the literal itself. 不是文字本身。

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

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