Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Swapping pointed-to variables [duplicate]

Tags:

c++

pointers

swap

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!

like image 905
tomKPZ Avatar asked Feb 18 '23 05:02

tomKPZ


2 Answers

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.

like image 52
j_random_hacker Avatar answered Feb 27 '23 01:02

j_random_hacker


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.

like image 37
Zeenobit Avatar answered Feb 27 '23 02:02

Zeenobit