c - 在 C 中的字符串文字中禁止使用

标签 c

在 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. The pmessage 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/

相关文章:

c - 取消引用 C 中的函数指针以访问 CODE 内存

c - 第二个 printf ("%d\n", n);被叫?

c - 有没有办法在一个线程而不是其他线程中关闭 stderr 的输出?

c - 在 GUROBI 的 C API 中添加约束需要太长时间

html - 获取以某种格式编码的 url 参数值

c - C语言中简单的凯撒密码,无需用户输入

c - C语言的扑克牌游戏。请解释花色[4][9]和花色[13][6]?

c - Windows XP 和 Windows 7 之间注销通知事件的差异

c++ - 查找目录中所有 .cpp .h 文件的常规方法(include、src 等...)

c - 以编程方式解决魔方