This is a sample snippet from a book. I am not understanding how it is printing the string in reverse. The first time reverse
is called, the element at 0 is not null assuming of course a valid string was entered. In the else
statement, we are calling the function again passing in the address of element at index 1.
So let's say I input "hello"
. Then I am passing the address of e
. The second time reverse
is called, however, how is the string being traverse? The index being checked is still 1. Also, it seems to me we are not replacing the values of the array. When we start printing the values with putchar
I get so confused that the value at index 0 starts with the last element of the array. I understand that when we use recursion and we hit the base case, and since the items are put on the stack, we start reading them from the top of the stack pointer until the end which is why is in reverse. But here I don't see that happening.
The hard-coded indexes at
reverse( &ptr[1]);
putchar(ptr[0]);
do not make sense to me. I guess I am having difficulty seeing how the string is being traverse when it is the same address being passed each time in the recursion. Please help me understand what is happening.
I have modified the code a bit for simplicity but it does the same thing the one in the book does.
#include <stdio.h>
void reverse(char * ptr);
int main(){
char sentence[10];
printf("enter text \n");
fgets(sentence, 10, stdin);
printf("The line is: \n");
reverse(sentence);
return 0;
}
void reverse( char * ptr){
if(ptr[0] == '\0'){
return;
} else{
reverse( &ptr[1]);
putchar(ptr[0]);
printf("\n");
}
}