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;
}
The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.
Pointer is a variable which stores the memory address of another variable. The first pointer is used to store the address of second pointer. That is why they are also known as double pointers Triple Pointer: Triple Pointer to the memory location where the value of a single-pointer is being stored.
When you pass in a pointer to a function, the address value is being copied over to the function parameter. Due to the function's scope, that copy will vanish once it returns. By using a double pointer, you will be able to update the original pointer's value.
In C parameters are passed by value. This means that in test1
when you pass pp
a copy is made of the pointer and when you change it the change is made to the copy not the pointer itself. With test2
the copy is of a double pointer but when you dereference and assign here
*pp = &myVar;
you are changing what is being pointed to, not changing pp
itself. Take note that this behaviour in test2
is undefined as is documented in some of the other answers here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With