I have been writing a program that is quite complex compared to what I have dealt with until now. Anyways at some point I am supposed to write a function that will manipulate a struct list. I’m trying to make this question as simple as possible so I wrote down a pretty simple piece of code just for reference.
Here is the thing: at first I call testf from another function providing it with a valid current as well as an i with a value of 0. This means that testf will call itself about 100 times before it starts accessing the rest of the code. This is when all the generated instances of testf will start getting resolved.
void testf(listnode *current, int *i) {
wordwagon *current2;
current2 = current;
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(current2, i);
}
current = current->next;
return;
}
If, let’s say, I have enough connected list nodes at my disposal, is current = current->next; the correct way for the “last” testf function to access and edit the caller’s current2 value (which is this function’s current), or am I horribly wrong?
If I am, what is the way to make changes to the caller function’s variables from inside the called function and be sure they won’t go away as soon as the called function returns? I find it kind of hard to get a good grasp on how pointers work.
It is very likely that I have left out important information or that I haven’t asked my question clearly enough. Please inform me if that is the case so I can edit in whatever you need.
Thanks in advance.
You can pass pointer to a pointer in your function, and derefrence it to get a listnode pointer back , here is how the code will look like after that ( not tested for compilation ) :
Here is a list of really good articles for learning pointers :
a) http://cslibrary.stanford.edu/102/PointersAndMemory.pdf
b) http://cslibrary.stanford.edu/103/LinkedListBasics.pdf