Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need of Pointer to pointer

Tags:

c

pointers

What is necessary for storing the address of a pointer?

  int a = 2;
  int *p = &a;
  int **q = &p;

Any practical use? Real time applications.

like image 946
Gibbs Avatar asked Aug 19 '13 05:08

Gibbs


2 Answers

In C you can either pass "value" or "address" of an object. If you pass value in function call, then changes made in the function don't reflect at calling place. And to reflect changes, you need to pass address of the object, for example:

void insert(node* head){
   head->data = 10;    // address(or head) is still same 
}

By object I means any type int, char or struct e.g. node

In the above example you change value at addressed by head pointer and change in data will be reflected.

But suppose if you want to change head itself in your list (e.g. insert new node as first node).

void insert(node* head){
   head = malloc(sizeof(head));  // head changed 
   head->data = 10;
}

Then value doesn't reflect at calling place because this head in function is not the same as head at calling place.

You have two choice, either return head or use pointer to pointer (but remember only one value can be return).

Use pointer to pointer:

void insert(node** head){
   (*head) = malloc(sizeof **head);   
   (*head)->data = 10;
}

Now changes will reflect!

The point is, if address is your value (need to updated address), then you need to use pointer of address or I should say pointer to pointer to reflect changes at the calling place.

As your question is what is need of pointer to pointers, one more place where pointer to pointer used in array of string, and dynamic 2-D arrays, and for same use you may need pointer to pointer to pointer for example dynamic matrix of String or/ 3D char array.

Read also this:Pointers to Pointers I just found, to tell you for an example.

like image 157
Grijesh Chauhan Avatar answered Nov 13 '22 07:11

Grijesh Chauhan


A ** is just a pointer to a pointer. So where an *p contains the address of an p, p** contains the address of an p* that contains the address of an p object.

** is used when you want to preserve the Memory-Allocation or Assignment even outside of a function call.

Also check this article.

EXAMPLE:-

void allocate(int** p)
{
  *p = (int*)malloc(sizeof(int));
}

int main()
{
  int* p = NULL;
  allocate(&p);
  *p = 1;
  free(p);
}
like image 11
Rahul Tripathi Avatar answered Nov 13 '22 05:11

Rahul Tripathi