`我正在尝试编写一个程序来反转两个字符串,虽然我已经做得很好但是当我运行它时,程序运行到第 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/