I’ll say in advance that I’m asking about pointers to pointers, so my words may be a bit vague, but try to stay with me 🙂
I am trying to understand how changing a pointer passed as an argument takes effect outside the scope of the function. So far this is what I understand: if a pointer is passed as an argument to a function, I can only change what the pointer points to, and not the pointer itself (I’m talking about a change that will take effect outside the scope of the function, as I said). And if I want to change what the pointer is pointing to, I have to pass a pointer to a pointer.
Am I right so far?
Also, I’ve noticed that when I have a struct that holds some pointers, if I want to initialize those pointers I have to pass the struct to the initialization function as a pointer to pointer. Is this for the same reason?
You are right in the first bit but if you’ve allocated the struct then you can pass a pointer to it. However, if the function allocated the struct, then either you use the function return to collect the value of the newly allocated struct or you pass in a pointer to a pointer in the parameter list.
(I’ve not got a c compiler to hand but I’ve tried to write some examples).
int main() { struct x *px = malloc(...); initx(px); } void intix(struct x* px){ px-> .... }int main() { struct x *px = initx(); } struct x* intix(){ struct x *px = malloc(...); px-> .... return px; }int main() { struct x *px; initx(&px); } void intix(struct x** ppx){ struct x *px = malloc(...); px-> .... *ppx = px; }