分段错误错误

bla*_*edj 4 c++ segmentation-fault

`我正在尝试编写一个反转两个字符串的程序,虽然我做得很好但是当我运行它时,程序运行到第26行,然后我得到分段错误错误.该程序编译良好.我想知道我的功能是否有一个简单或明显的问题,我没有看到,任何帮助将不胜感激!

提前致谢

#include <iostream>
#include <string>
using namespace std;

// Reversing the characters in strings.

void reverse(string str);
void swap(char * first, char *last);

int main() {
    // declarations and initialization
    string str1;
    string str2;

    cout << "Please enter the first string of characters:\n";
    cin >> str1;

    cout << "Please enter the second string of characters:\n";
    cin >> str2;

    cout << "The strings before reversing are:" << endl;
    cout << str1 << " " << str2 << endl;

    // reverse str1
    reverse(str1);
    // reverse str2
    reverse(str2);

    // output
    cout << "The strings after reversing: " << endl;
    cout << str1 << " " << str2 << endl;

    return 0;
}

void reverse(string str) {
    int length = str.size();

    char *first = NULL;
    char *last = NULL;
    first = &str[0];
    last = &str[length - 1];
    for (int i = 0; first < last; i++) {
        swap(first, last);
        first++;
        last--;
    }
}

void swap(char *first, char *last) {
    char * temp;

    *temp = *first;
    *first = *last;
    *last = *temp;
}
Run Code Online (Sandbox Code Playgroud)

Moo*_*uck 6

我不知道26号线在哪里,但是

char * temp;
*temp = ...
Run Code Online (Sandbox Code Playgroud)

无效. temp应在指出char,或(更好的)重写功能的地方temp 一个char.

Seth Carnegie观察到string如果你想修改原件,你必须通过引用传递s.

void reverse(string& str) { //pass by reference, so origional is modified
Run Code Online (Sandbox Code Playgroud)