我认为字符串文字是只读的?

Ren*_*llo 1 c++

char* a = "string"; /*"string" is a string literal, thus modifying
value isn't allowed, but then why */
char b[] = "string1"; /*"string1" is
also a string literal but why modification of this is allowed? */

a[1] = 's'; //this is not allowed b[1] = 'p'; //this is allowed
Run Code Online (Sandbox Code Playgroud)

为什么 char 数组明确指向字符串文字时可以修改?

son*_*yao 5

当它明确指向字符串文字时?

不。给定的char b[] = "string1";不是b一个指向字符串文字的指针,而是一个char包含 的副本的数组"string1"。对字符串文字的修改会导致 UB,但对char数组的修改则没问题。

字符串文字可用于初始化字符数组。如果像这样初始化一个数组char str[] = "foo";str将包含该字符串的副本"foo"

顺便说一句,char* a = "string";自 C++11 起不允许使用;你必须把它写成const char* a = "string";.