#include <stdio.h>
int main() {
char x[] = "hello";
char *y = "world";
*y = x[1];
printf("%s", y);
return 0;
}
有人可以帮我理解为什么这段代码无法编译吗?
最佳答案
字符串文字在 C 中是不可变的。任何修改字符串文字的尝试都会导致未定义的行为。
来自 C 标准(6.4.5 字符串文字)
7 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.
您可以使用由字符串文字初始化的数组,而不是字符串文字本身。例如
char x[] = "hello";
char y[] = "world";
*y = x[1];
请注意,根据 C 标准,不带参数的函数 main 应声明如下
int main( void )
此外,如果您将程序编译为 C++ 程序,那么编译器也会针对该语句发出错误
char *y = "world";
因为在 C++(与 C 相反)中,字符串文字具有常量字符数组类型。所以在这种情况下有效的声明是
const char *y = "world";
关于c - 变量点等于数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545455/