Recursion problem, C language

Asked

Viewed 61 times

2

I have a problem, in a code I found where it receives a string from the user and returns it reversed, doing this recursively.

However, I do not understand why the function made can actually do this.

Follows the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void recebeString(char *string)
{
    if(*string)
    {
        recebeString(string+1);
        putchar(*string);

    }

}

int main()
{
    char resultado[250];

    printf("Escreva uma string(frase): ");
    scanf("%[^\n]",resultado); // força o scanf a ler ate encontrar o \n.
    setbuf(stdin, NULL);

    printf("%s\n\n",resultado);

    recebeString(resultado);


    return 0;

}

someone can help me?

1 answer

3

What the function does is to call itself by increasing the string pointer, so the calls are stacked in memory, until a moment will come when the if will fail because it will find the \0 that ends the string (assuming the string is well formed). Then it will return to the last call at the point just before the putchar and will perform the putchar of the last character. And will continue to pop and calling putchar.

That’s why it works.

  • But, as the function starts straight at the end of the string?

  • It doesn’t start right at the end. It starts at the beginning, but the first call she makes is to herself and this stacks the execution without finishing, so the first character is waiting to be printed. When it arrives at the end and no longer passes in if it returns and the first character stacked to be printed is the last of the string, it prints and returns to the penultimate and so on until it reaches the first one again.

  • Got it! , vlw guy helped abeça!

  • 1

    I don’t know if you’ve used stackoverflow before, but if a reply helps you can mark it as accepted. You can also give an upvote.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.