In-Place String Reverse in C

爱⌒轻易说出口 提交于 2019-12-04 06:31:04

问题


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;
}

回答1:


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




回答2:


You are trying to change a string literal which leads to undefined behavior.

Change

char* a = "12";

to

char a[] = "12";



回答3:


Because end and str point to the same memory location -> they're two different names of the same object. You can avoid using two variables:

char foo[20] = "abcdefghi", tmp;
int counter = 0, length = strlen(foo);

for(counter, counter < length / 2; counter++) {
    tmp = foo[counter];
    foo[counter] = foo[length - counter];
    foo[length - counter] = tmp;
}


来源:https://stackoverflow.com/questions/4785967/in-place-string-reverse-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!