#include <stdio.h>
void reverse( const char * const sPtr );
int main ( void ) {
char sentence[ 80 ];
fgets( sentence, 80, stdin);
reverse (sentence);
return 0;
}
void reverse( const char * const sPtr ){
if (sPtr[0] == '\0' )
return;
else {
reverse( &sPtr[1] );
putchar (sPtr [0] );
}
I’m confused in generally about how the reverse function is working? I do not see how the Pointer is being incremented to point the next charcter, and I don’t know if I understand exactly what putchar does. Any help would be appreciated.
This function is recursively calling itself for every successive character in the string and on reaching the
\0character, which is the base case, is unwinding printing the characters in reverse order.Step 1 :
Here, sPtr points to the first character of the string.
Step 2 :
This line is what takes the function forward.
Step 3 :
Repeat these two steps you reach the end of the string, the base case.
It is not reversing the string but simply printing the string in reverse.