我想做一个反向字符串函数,我已经这样做了:

void reverse_str(char s[])  {
    int i, j;
    char ch;
    for(i = 0, j = strlen(s) - 1; i < j; i++, j--)  {
        ch = s[i];
        s[i] = s[j];
        s[j] = ch;
    }
    return ;
}

但由于某些原因,当我将i < j更改为i != j时,会出现分段错误。当ij是指针时,也会发生这种情况。为什么?

最佳答案

几乎可以肯定的是,因为ij相互传递(无论它们是索引还是指针在这里都无关紧要)。例如,任何字符数为偶数的字符串都会出现此问题。
请考虑字符串的以下顺序:

     0123 <- indexes
     ----
s = "drum", i = 0, j =  3, swap d and m.
s = "mrud", i = 1, j =  2, swap r and u.
s = "murd", i = 2, j =  1, swap u and r, oops, we've passed each other.
s = "mrud", i = 3, j =  0, swap m and d.
s = "drum", i = 4, j = -1, swap who knows what, undefined behaviour.

注意,对于奇数长度的字符串,您不会遇到这个问题,因为drum最终等于i(中间字符)。
j检查还解决了这个问题,因为它同时检测指针的相等性和相互传递的指针。

07-24 18:29
查看更多