Can someone explain / give a reasoning to me on why the value of variable i in main function in below code snippet does not change via function test1 while it does change via test2? I think a single pointer should be sufficient to change the value of i. Why are we supposed to use double pointer?
#include <stdio.h>
void test1(int* pp)
{
int myVar = 9999;
pp = &myVar;
}
void test2(int** pp)
{
int myVar = 9999;
*pp = &myVar;
}
int main()
{
printf("Hej\n");
int i=1234;
int* p1;
p1 = &i;
test1(p1);
printf("does not change..., p1=%d\n",*p1);
test2(&p1);
printf("changes..., p1=%d\n",*p1);
return 0;
}
In C parameters are passed by value. This means that in
test1when you passppa copy is made of the pointer and when you change it the change is made to the copy not the pointer itself. Withtest2the copy is of a double pointer but when you dereference and assign hereyou are changing what is being pointed to, not changing
ppitself. Take note that this behaviour intest2is undefined as is documented in some of the other answers here