在 K&R 书的第 104 页,我看到了这个声明:
char amessage[] = "now is the time"; //an array char *pmessage = "now is the time"; //a pointer
Individual characters within the array may be changed but
amessage
will always refer to the same storage. Thepmessage
pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents...
那么,这就是他们在这两种情况下所指的错误吗?
对于数组,
amessage[] = "allocate to another address"; //wrong?
对于指针,
pmessage[0] = 'n'; //wrong?
我只想知道什么时候有人违反了这些规则。
谢谢。
最佳答案
/* 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';
请注意,在 C 中您不能分配数组,因此如果您想复制一个数组,请使用 memcpy
函数或使用 strcpy
函数来复制一个字符串。
关于c - 在 C 中的字符串文字中禁止使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11691324/