我写了以下代码:
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
这给了我一个分段错误,我不明白为什么。
str
不是。pointer to char
_ const char
即使是这种情况,它也不应该给出如下程序的编译错误:
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
它给出了一个错误:assignment of read-only location *str
。
编辑
如果我的代码将指针指向只读位置,我不应该得到编译错误吗?