When to use Pointer-to-Pointer in C++?

We basically need pointer to pointer when we want to change the address of the pointer it is pointing to. very good example will be the case of linked list where we send a pointer to pointer to the head node when we try to insert a value to the beginning. Snippet of code pasted below.

int main()
{
    /* Start with the empty list */
    struct node* head = NULL;
    
    /* Use push() to construct below list
        1->2->1->3->1  */
    push(&head, 1);
    push(&head, 2);
    .....
    ....
}
    
/* Given a reference (pointer to pointer) to the head
   of a list and an int, push a new node on the front
   of the list. */
void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node = (struct node*) malloc(sizeof(struct node));
    .....
    .....
}

This is basically because, say a pointer was initially pointing to a memory location 0X100 and we want to change it to point it to some other location say 0X108. In such case pointer to pointer is passed.


When you want to change the value of variable passed to a function as the function argument, and preserve updated value outside of that function, you require pointer(single pointer) to that variable.

void modify(int* p)
{
  *p = 10;
}

int main()
{
  int a = 5;
  modify(&a);
  cout << a << endl;
}

Now when you want to change the value of the pointer passed to a function as the function argument, you require pointer to a pointer.

In simple words, Use ** when you want to preserve (OR retain change in) the Memory-Allocation or Assignment even outside of a function call. (So, Pass such function with double pointer arg.)

This may not be a very good example, but will show you the basic use:

void safe_free(int** p) 
{ 
  free(*p); 
  *p = 0; 
}

int main()
{
  int* p = (int*)malloc(sizeof(int));
  cout << "p:" << p << endl;
  *p = 42;
  safe_free(&p);
  cout << "p:" << p << endl;
}

When to use Pointer-to-Pointer in C++?

I'd say it is better to never use it in C++. Ideally, you will only have to use it when dealing with C APIs or some legacy stuff, still related to or designed with C APIs in mind.

Pointer to pointer has pretty much been made obsolete by the C++ language features and the accompanying standard library. You have references for when you want to pass a pointer and edit the original pointer in a function, and for stuff like a pointer to an array of strings you are better off using a std::vector<std::string>. The same applies for multidimensional arrays, matrices and whatnot, C++ has a better way of dealing with those things than cryptic pointers to pointers.

Tags:

C++