gpt4 book ai didi

c - 获取字符串文字的地址或对其进行迭代是否有效?

转载 作者:太空狗 更新时间:2023-10-29 15:54:13 25 4
gpt4 key购买 nike

这样做当然是有效的:

char src[] = "Allie has a cat.";
char buff[20];
strcpy(buff, src);
printf("%s\n", buff);

或者这个:

printf("Allie has a cat.\n");

但是,将上面的代码缩短为这样有效吗?

char buff[20];
strcpy(buff, "Allie has a cat.");
printf("%s\n", buff);

或者写成:

printf("%s", "Allie has a cat.");

我问的原因是 C 字符串文字中的 AFAIK 与字符数组有些不同,虽然这两个示例似乎都有效( ideone#1ideone#2 ),但我认为当涉及到 C I不应该做任何我认为应该有效的事情,或者只是似乎正在工作 b/c 这种语言有多少陷阱,以及用这种语言编写一个看起来无辜但实际上是 UB 的结构是多么容易。

最佳答案

这是完全正确的。字符串文字是字符数组:

6.4.5 String literals

[...]

  1. In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]

  2. It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

(来源:ISO 9899:1999(“C99”))

有点像

strcpy(buff, "Allie has a cat.");

实际上等同于

static char __s0[] = "Allie has a cat.";
strcpy(buff, __s0);

(除了修改字符串文字有未定义的行为)。

关于c - 获取字符串文字的地址或对其进行迭代是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44210096/

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