- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这样做当然是有效的:
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#1 , ideone#2 ),但我认为当涉及到 C I不应该做任何我认为应该有效的事情,或者只是似乎正在工作 b/c 这种语言有多少陷阱,以及用这种语言编写一个看起来无辜但实际上是 UB 的结构是多么容易。
最佳答案
这是完全正确的。字符串文字是字符数组:
6.4.5 String literals
[...]
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 [...]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/
我是一名优秀的程序员,十分优秀!