Segmentation fault error

Hello,
I am trying to write a program that reverses two strings, I though I had it done pretty well but when I run it, the program runs till line 26, then I get a segmentation fault error. The program compiles fine. I am wondering if there is a simple or obvious problem in my functions that I am not seeing, Any help would be appreciated!!

Thanks in advance,
-Blaed


#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;
}

you just cannot do it like you do it in your 'reverse()'. string is not an array?

Look at this http://www.cplusplus.com/reference/string/string/rbegin/ how to reverse a string
Topic archived. No new replies allowed.