可能是重复问题:
为什么在写字符串时我会收到分段错误?
我有以下程序:
#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