【发布时间】:2012-12-12 21:47:41
【问题描述】:
可能重复:
Why do I get a segmentation fault when writing to a string?
下面的简单函数应该就地反转一个字符数组。
void reverse(char* str)
{
char* last = str;
// find end of the string
while(*last) {
++last;
}
// swap characters until the pointers meet in the middle
while(str < last)
{
--last;
char temp = *str;
*str = *last;
*last = temp;
++str;
}
}
int main()
{
char* a= "Hello";
reverse(a);
return 0;
}
代码编译。但它会引发有关访问冲突的运行时错误。根据调试器,罪魁祸首是以下行:
char temp = *str;
任何想法为什么会发生?
【问题讨论】:
-
这不再是有效的 C++ 代码,并且有充分的理由。
-
您包含
<iostream>但不使用任何流,您使用using namespace std但不使用该命名空间中的任何内容。