可能重复:
Why do I get a segmentation fault when writing to a string?为什么这个程序没有给出预期的输出?
int main()
{
char *c = "abc";
*c = 'd';
printf("%s",c);
return 0;
}
当我试图运行这个程序在C,那么crashes..I想知道什么是错误这里的程序?
可能重复:
Why do I get a segmentation fault when writing to a string?为什么这个程序没有给出预期的输出?
int main()
{
char *c = "abc";
*c = 'd';
printf("%s",c);
return 0;
}
当我试图运行这个程序在C,那么crashes..I想知道什么是错误这里的程序?
因为字符串文字abc
实际上存储在进程的只读区域中,所以不应该修改它。操作系统已将相应的页面标记为只读,并且您在尝试写入时遇到运行时异常。
每当你一个字符串分配给char
指针,始终有资格作为const
使编译器警告你这样的问题:
const char *c = "abc";
*c = 'd'; // the compiler will complain
如果你真的想修改一个字符串(虽然不能直接本身,而是它的拷贝),我会建议使用strdup
:
char *c = strdup("abc");
*c = 'd'; // c is a copy of the literal and is stored on the heap
...
free(c);
“char *'指针”将是一个char **。 –
@Samuel:正确:-) –
是一个字符串文字。
*c = 'd'
是尝试修改该字符串文字。
您不能修改字符串文字。
请注意,在某些平台上,您可以修改字符串文字。 –
@WilliamPursell:试图修改字符串文字会导致未定义的行为。即使它不会在某个平台上崩溃,也会导致其他错误(例如更改不同的字符串)。 – interjay
@WilliamPursell:如果你想让你的程序展现出定义好的行为,你就不能这样做。 –
'C'指向一个字符串文字而这又不可修改的。但你想改变的人物之一。 –
如果你想知道,'char c [4] =“abc”;'会起作用。 –