4

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I have the following program:

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

However, I'm having trouble swapping the values to which the pointers point. I thought *p = *p1 should just set the pointed-to value of p to the pointed-to value of p1, but something seems bugged up. Thanks in advance for any help!

4

3 回答 3

7

The code looks fine to me. The most likely problem is that the compiler is allowed to assume that string literals are not modified, so it can put them in read-only memory. Try

char s[] = "Hello";

in main() instead, which creates a writable copy of the string literal.

于 2012-12-08T05:46:27.830 回答
1

An alternative solution to @j_random_hacker:

char* buffer = new char[32];
strcpy(buffer, "Hello");
reverseString(buffer, buffer + strlen(buffer) - 1);

... rest of your program ...

delete[] buffer;

This properly allocates memory for a C-style string which can then be modified by any function. Of course, you need to include <string.h> header to access strcpy and strlen.

于 2012-12-08T06:06:08.713 回答
0

Header file for strlen() is missing.

Second, it throws a warning - Deprecated conversion from string constant to char*, @j_random_hacker's solution seems to take care of this issue.

于 2012-12-08T05:56:46.530 回答