Question

I tried to run a reverse string function by using the code from Cracking the coding interview. I don't know if the code is wrong or I should use another IDE (I used Xcode 5.2 for this one). I'm new to C programming so please explain. Thanks.

#include <stdio.h>

void reverse(char *str);

int main(int argc, const char * argv[])
{

  char *str = "Hello, World!";
  reverse(str);
  printf("%s", str);
  return 0;
}

void reverse(char *str){
  char *end = str;
  char tmp;
  if (str) {
    while (*end) {
      ++end;
    }
    --end;

    while (str < end) {
      tmp = *str;
      *str++ = *end;
      *end-- = tmp;
    }
  }
}
Was it helpful?

Solution

The problem here is that you try to modify a string literal (str points to that) and string literals are constant (i.e. read-only, non modifiable).

Trying to modify something constant is undefined behavior. Undefined behavior may sometimes seem to work, but most of the time it will cause a crash at runtime.

A good advice to find possible cases of undefined behaviors (or other things that might be bad) is to enable more warnings. Then you should get a warning about assigning a constant array (all string literals are constant arrays) to a non-constant pointer.

OTHER TIPS

char *str = "Hello, World!";

make it

char str[] = "Hello World!";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top