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?
But, as the function starts straight at the end of the string?
– Dennis Paiva
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.
– prmottajr
Got it! , vlw guy helped abeça!
– Dennis Paiva
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.
– prmottajr