Need of Pointer to pointer

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.

Leave a Comment