可能重複:
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