Usually if your recursive function needs loops or static variables, it's a hint that it's not designed correctly. As a matter of fact, those two things make your program quite hard to follow.
It helps to say something more than just "entered reverse". Try this for your reverse function. The algorithm is the same, I just added a little extra info:
Code:
void reverse(char * input,char *reversed)
{
static int depth = 1;
static int i = 0;
printf("Entering reverse, depth = %d, input = %s\n", depth, input);
while(*++input != '\0') {
depth++;
reverse(input,reversed);
}
reversed[i] = *--input;
reversed[i+1] = '\0';
i++;
depth--;
}
Notice that input shrinks then grows, then shrinks then grows. You call it first with "Keshav", at a recursive depth of 1 (i.e. one instance of the reverse() function on the call stack). That loops through the string, calling reverse with "eshav", "shav", "hav", "av", and "v", each with a recursive depth of 2. Each of those then loops through every letter in the string it was passed, so at depth 2, "eshav" calls reverse with "shav", "hav", "av" and "v", each with depth 3. This goes on to a depth of 6.
You need to define a proper base case, which would be when input points to the null terminator of the original string. You should also start reverse at the end of the allocated memory:
Code:
int main(void)
{
char input[] = "Keshav";
char *reversed = malloc(strlen(input) + 1);
reverse(input, reversed + strlen(input) - 1)
// null terminate reversed, print output and free(reversed)
return 0;
}
void reversed(char *input, char *reverse)
{
if (*input == '\0') // base case, do nothing
return;
// no loops or static variables, just assign through the pointers and increment/decrement, then recurse
}