Pointer to a pointer is required when you want deal with storing pointer and dealing with it; e.g. to change the content of the underlying pointer. For example:
int i = 0, j = 1;
int* p = &i;
int** pp = &p;
Now you want to make p
point to j
instead of i
, then you can do as:
*pp = &j; // equivalent to `p = &j;`
This is just for explanation. In real world this is required when you are dealing with functions.
void Destroy (int** pp) { // for any int pointer
delete[] pp; // deallocate the memory
*pp = 0; // set the pointer to 0, so that it's not dangling
}
And use it as:
int* pi = new int[30];
...
Destroy(&pi); // `pi` is now pointing to 0
But still in C++, you have superior alternative as "pointer reference". Which does mostly the same thing, but with better readability.
void Destroy (int*& p) { // for any `int` pointer
delete[] p; // destroy the memory
p = 0; // Null out the same pointer which was actually passed
}
use as:
Destroy(pi); // no need to pass address