tags:

views:

140

answers:

2

Why does this piece of code throw an exception when I try to change a character in the string

void reverseString(char *s)
{
    int e = strlen(s) - 1;
    int b = 0;
    char t1,t2;

    while(b < e)
    {
        t1 = s[b];
        t2 = s[e];
        s[b] = t2;
        s[e] = t1;
        b++;
        e--;
    }
} 
+4  A: 

My guess is that the string you are testing it on is stored in read-only memory. Did you define it with a string literal?

Added later to elaborate:

If you do this,

char *s = "Hello";
reverseString(s);

you will probably crash, because the string can be stored in read-only memory, and most compilers will put it there.

If on the other hand, you write,

char s[6];
sprintf(s, "Hello");
reverseString(s);

it will work.

Jive Dadson
According to a comment that the OP just added, this is indeed the answer. So why the down-vote? Mis-click, one hopes.
Jive Dadson
Thank you, this is exactly what I was doing wrong.
+2  A: 

Don't reinvent the wheel, use standard library's algorithms: std::reverse

void reverseString(char *s) {
  std::reverse(s, s + strlen(s));
}

void reverseString(std::string &s) {
  std::reverse(s.begin(), s.end());
}

Note: std::string is mutable.

phadej
I think that he's "reinventing the wheel" for exercise; if not, well, then you have a valid point. :)
Matteo Italia
@Matteo better exercise is to reinvent the `std::reverse` :)
phadej
Well, this is out of discussion (although I think that there isn't much difference from the algorithm point of view). :)
Matteo Italia