可能重复:
为什么在写入字符串时会出现分段错误?
我有以下程序:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法交换指针指向的值.我认为*p =*p1应该只是将p的指向值设置为p1的指向值,但似乎有些东西被搞砸了.在此先感谢您的帮助!
代码看起来很好.最可能的问题是允许编译器假定字符串文字未被修改,因此它可以将它们放在只读内存中.尝试
char s[] = "Hello";
Run Code Online (Sandbox Code Playgroud)
在main()相反,它创建了一个可写副本的字符串字面的.
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           108 次  |  
        
|   最近记录:  |