Amir Jalilifard Amir Jalilifard - 13 days ago 6
C++ Question

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

I was wondering when we use Pointer to Pointer in C++ and why we need to point to a pointer? I know that when we point to a pointer it means we are saving the memory address of a variable into the memory but I don't know why we need it? Also I have seen some examples that always the use Pointer-to-pointer in creating a Matrix! But why a Matrix may need Pointer to Pointer?

Answer

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;
}