可能重复时:
Why do I get a segmentation fault when writing to a string?访问冲突错误逆转串C++
下面的简单函数应扭转到位的字符阵列。
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++代码,并有很好的理由。 – Puppy
您包含'',但不要使用任何流,并且您使用'using namespace std',但不要使用该名称空间中的任何内容。 –
dreamlax