c++ - 段错误

标签 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;
}

最佳答案

我不知道第26行在哪里,但是

char * temp;
*temp = ...

无效。 temp 应该指向一个 char,或者(更好的是)将函数重写为 temp 字符

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

void reverse(string& str) { //pass by reference, so origional is modified

关于c++ - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8161239/

相关文章:

c - memmem() 的段错误

python - 使用jpype启动jvm时出现段错误

python - Python 导演类中的 Swig 异常

c++ - 如何使用 NDIS_SUPPORT_NDIS630 将 NDIS 6.2 移植到 NDIS 6.3?

c++ - 3d 相机 - 如何改变相机方向?

c++ - 安全段错误?

c - 信号 SIGTRAP 免费崩溃

c++ - 在 Eigen C++ 中广播(两个) vector

c++将整数转换为字符串ubuntu

linux - "Unexplainable"核心转储