7.5 Pointer to Pointer
A pointer is itself a variable, so it also has its own address. A pointer that points to a pointer is called a pointer to pointer, written int **.
cpp
int data = 5;
int *p = &data; // first-level pointer, points to data
int **q = &p; // pointer to pointer, points to p
std::cout << data << std::endl; // 5
std::cout << *p << std::endl; // 5
std::cout << **q << std::endl; // 5q stores the address of p. So *q is p, and **q dereferences once more to reach data. Each extra * follows one more address.
Loading interactive lab...
Loading concept check...
Loading practice...
Letting a function modify the caller's pointer
The most common use of a pointer to pointer is to let a function modify the caller's pointer. If you pass only an int *, the function changes a copy of the pointer; to change the caller's pointer itself, pass an int **.
cpp
void allocate(int **out) {
*out = new int;
**out = 7;
}
int main() {
int *q = nullptr;
allocate(&q); // q now points to fresh memory
std::cout << *q << std::endl; // 7
delete q;
return 0;
}argv is a pointer to pointer
In main(int argc, char* argv[]), argv behaves like a char**: it points to a set of string pointers, where each argv[i] is a string (see 6.3 for command-line arguments).
Loading practice...