C ++: switching pointer variables

Possible duplicate:
Why does a segmentation error occur 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 was having trouble replacing the values โ€‹โ€‹that the pointers point to. I thought that * p = * p1 should just point p to the specified p1, but something seems distorted. Thanks in advance for your help!

+4
source share
3 answers

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

 char s[] = "Hello"; 

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

+7
source

Alternative solution for @j_random_hacker:

 char* buffer = new char[32]; strcpy(buffer, "Hello"); reverseString(buffer, buffer + strlen(buffer) - 1); ... rest of your program ... delete[] buffer; 

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

+1
source

The header file for strlen () is missing.

Secondly, it issues a warning. Outdated conversion from string constant to char *, the @j_random_hacker solution seems to take care of this problem.

0
source

All Articles