Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double pointer vs single pointer

Tags:

c

pointers

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;
}
like image 347
F. Aydemir Avatar asked Dec 04 '12 12:12

F. Aydemir


People also ask

What is the difference between double pointer and single pointer?

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.

What is a single pointer?

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.

What is double pointer in linked list?

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.


1 Answers

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

like image 145
mathematician1975 Avatar answered Oct 09 '22 03:10

mathematician1975