I was working on a function where I wanted to pass a parameter as a pointer and assign its value inside the function. I got to a solution with using a pointer to a pointer and using a pointer alone. It made scratch my head on when would a pointer to a pointer be required if a pointer can act exactly the same when assigning a pointer's value from a parameter?
View my sample code below.
// pointers.c
void foo(int *f) {
*f = 1;
}
void bar(int **f) {
int y = 2;
int *temp = &y;
(*f) = temp;
}
void baz(int *f) {
int y = 3;
int *temp = &y;
f = temp;
}
int main(int argc, char const *argv[]) {
int j = 0;
int *num = &j;
printf("%d\n", *num);
foo(num);
printf("%d\n", *num);
bar(&num);
printf("%d\n", *num);
baz(num);
printf("%d\n", *num);
return 0;
}
$ gcc pointers.c -o pointers -Wall && ./pointers
0
1
2
3
The accepted answer in Why use double pointer? or Why use pointers to pointers?, does not comeback with why in C a double pointer would be required to use.