gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:30 26 4
gpt4 key购买 nike

在 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/24829358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com