Search code examples
cstringreversein-place

In-Place String Reverse in C


I am trying to learn the fundamentals of C, but I cannot figure out why this code doesn't work. The while loop in reverse() causes a bus error. I found almost identical code in a programming interview book as a valid solution, but neither this nor other similar methods I have seen posted here work for me without a bus error.

#include <stdio.h>

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

int main() {
 char* a = "12";
 puts(a);
 reverse(a);
 puts(a);

 return 0;
}

Solution

  • The problem is that you're trying to reverse a constant literal string, which is read only. Change the declaration of a in main to char a[] = "12"; to make it a writable char array instead