C中的字符串文字中的forbiddens

hel*_*esk 3 c

在K&R书籍第104页,我发现了这句话:

char amessage[] = "now is the time"; //an array
char *pmessage = "now is the time";  //a pointer
Run Code Online (Sandbox Code Playgroud)

可以更改阵列中的各个字符,但amessage 始终引用相同的存储.pmessage随后可以将指针修改为指向其他位置,但如果您尝试修改字符串内容,结果将是未定义的...

那么,这是他们在两种情况下的错误吗?

对于阵列,

amessage[] = "allocate to another address"; //wrong?
Run Code Online (Sandbox Code Playgroud)

对于指针,

pmessage[0] = 'n'; //wrong?
Run Code Online (Sandbox Code Playgroud)

我只是想知道什么时候违反这些规则.

谢谢.

oua*_*uah 6

/* OK, modifying an array initialized by the 
 * elements of a string literal */
amessage[0] = 'n';

/* not OK, modifying a string literal.
 * String literals are non-modifiable */
pmessage[0] = 'n';
Run Code Online (Sandbox Code Playgroud)

请注意,在C中您无法分配数组,因此如果要复制数组使用memcpy函数或使用strcpy函数来复制字符串.