2

this is my first post.

I have this function for reversing a string in C that I found.

    void reverse(char* c) {
        if (*c != 0) {
            reverse(c + 1);
        }
        printf("%c",*c);
    }

It works fine but if I replace:

reverse(c + 1);

with:

reverse(++c);

the first character of the original string is truncated. My question is why would are the statements not equivalent in this instance?

Thanks

4

4 に答える 4

7

の値を変更しc + 1ないため、変更します。c++c

于 2010-12-26T04:33:16.397 に答える
4

Let's expand on Fred's answer just a bit. ++c is equivalent to c = c+1, not c+1. If you replace the line reverse(c+1) with reverse(++c), then c is changed. This doesn't matter as far as the recursive call is concerned (why?) but means c is pointing somewhere new in the printf.

于 2010-12-26T04:39:05.297 に答える
2

c + 1変更しないc

++ccをインクリメントしてから、置き換えられた再帰呼び出しで新しい値を使用します。reverse(++c)

于 2010-12-26T04:33:55.380 に答える
1

As noted, ++c changes the value of c but c+1 does not.

This does not matter in the recursive call itself: reverse(c+1) and reverse(++c) will pass the same value to reverse; the difference happens when you use c in a printf after the recursive call -- in the ++c case, the value of c has been changed by the time you reach the printf.

于 2010-12-26T04:41:02.077 に答える