0

我从互联网上获得了此代码,但我无法获得整个代码。例如if(*str)。这段代码是什么意思?还可以返回一个字符串吗?我认为 main 中的数组可以直接在函数中更改,但在这里它被返回了..

#include<stdio.h>
#define MAX 100
char* getReverse(char[]);

int main(){

    char str[MAX],*rev;

    printf("Enter  any string: ");
    scanf("%s",str);

    rev = getReverse(str);

    printf("Reversed string is: %s\n\n",rev);
    return 0;
}    

char* getReverse(char str[]){

    static int i=0;
    static char rev[MAX];

    if(*str){
         getReverse(str+1);
         rev[i++] = *str;
    }

    return rev;
}
4

1 回答 1

1

This is not the clearest example of recursion due to the use of the static variables. Hopefully the code generally seems clear to you, I suspect the part that is confusing to you is the same that was confusing to me at first.

if(*str){
     getReverse(str+1);
     rev[i++] = *str;
}

So line by line.

if(*str){

If we have not reached the null terminator.

     getReverse(str+1);

Call the getReverse function on the next character of the string. It seems pretty straight forward up to here. But it also seems like it may not actually reverse anything because this is the next line

     rev[i++] = *str;

We assign index i the character at the beginning of str and increment i but here is the tricky part. i may not be what you think. getReverse gets called before i is incremented. And i is static, so changes will persist between function calls. So, lets say we have a 5 letter word, let say "horse" we will end up with 6 calls on the stack to getReverse. The 6th will not do anything because that is where it finds the null terminator. The trick is that we will then go about resolving the calls in reverse order. First the call where str is pointing to 'e' will resolve and increment i because all the other ones are are still waiting for their calls to getReverse to return. So the last letters are actually the first ones to get added and increment i which is what can be confusing here.

于 2012-08-07T16:05:10.547 回答