#include <stdio.h>
#include <stdlib.h>
void reprint(char *a[]) {
if(*a) {
printf("%d ",a);
reprint(a+1);
printf("%s ",*a);
}
}
int main() {
char *coll[] = {"C", "Objective", "like", "don't", "I", NULL};
reprint(coll);
printf("\n");
return EXIT_SUCCESS;
}
As the more experienced will know, this prints the array in reverse. I don’t quite understand how!
I need help understanding what reprint(char *a[]) does. I understand pointer arithmetic to a degree, but from inserting printfs here and there, I’ve determined that the function increments up to the array end, and then back down to the start, only printing on the way down. However, I do not understand how it does this; all I’ve managed to understand by looking at the actual code is that if *a isn’t NULL, then call reprint again, at the next index.
The key to understanding this type of recursion is to know how stacks work.
First: each time reprint() calls itself with (a+1), then a+1 is pushed onto the stack. This means the called reprint() gets a copy of the char** as an argument. The calling reprint’s ‘a’ is not touched. Like you said, this goes on until the passed char ** is NULL, i.e. the last element in the array. Then the test ‘if (*a)’ becomes false and reprint will not be called any deeper.
Note at this point, all 5 calls to reprint are ‘waiting’ for it to return, so none of the printf’s after the recursive call to reprint haven’t been called yet. Also note that all 5 calls have their own ‘a’ pointer. This is essential.
Now, since the last call of reprint doesn’t call reprint anymore, it will just return. The second to last reprint, the one which has an ‘a’ pointing to the string “I”, can then continue with the next statement after the call to reprint, which is the printf of “I”. Once this is done, this function also returns. The third to last reprint, the one with ‘a’ pointing to the string “don’t” can then also continue and prints “don’t”, etc…