可能重复:
Why do I get a segmentation fault when writing to a string?C++:交换实现指向的变量
我有以下程序:
#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'。 – chris
我知道,但我真的很想知道为什么它没有按照我设置的方式工作。顺便提一下,谢谢你的提示。 – tomKPZ
您正在修改字符串文字。 – chris