In-Place String Reverse in C

后端 未结 3 1158
一生所求
一生所求 2021-01-27 16:45

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

相关标签:
3条回答
  • 2021-01-27 17:25

    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

    0 讨论(0)
  • 2021-01-27 17:39

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

    Change

    char* a = "12";
    

    to

    char a[] = "12";
    
    0 讨论(0)
  • 2021-01-27 17:44

    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;
    }
    
    0 讨论(0)
提交回复
热议问题