【发布时间】:2012-12-08 05:39:58
【问题描述】:
可能重复:
Why do I get a segmentation fault when writing to a string?
我有以下程序:
#include <iostream>
using namespace std;
void reverseString(char* first, char* last)
{
while(first < last)
{
cout << *first << " " << *last << endl; //for debugging; prints 'H' and 'o' then crashes
char temp = *last;
*last = *first; //this line crashes the program
*first = temp;
first++;
last--;
}
}
int main()
{
char* s = "Hello";
reverseString(s, s + strlen(s) - 1);
cout << s << endl;
}
但是,我在交换指针指向的值时遇到了麻烦。我认为 *p = *p1 应该只是将 p 的指向值设置为 p1 的指向值,但似乎有些问题。提前感谢您的帮助!
【问题讨论】:
-
如果你不需要自己实现这个,首选
std::reverse。 -
我知道,但我真的很想知道为什么它不像我设置的那样工作。顺便说一句,谢谢你的提示。
-
您正在修改字符串文字。