Reverse a string using recursion

老子叫甜甜 提交于 2019-12-12 10:18:11

问题


I got this code from the internet but I couldnt get the whole code. for example if(*str) . What does this code mean? and also can a string be returned? I thought that an array in main can be changed directly in a function but here its been returned..

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

回答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.



来源:https://stackoverflow.com/questions/11849341/reverse-a-string-using-recursion

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