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 **.
c
int data = 5;
int *p = &data; // first-level pointer, points to data
int **q = &p; // pointer to pointer, points to p
printf("%d\n", data); // 5
printf("%d\n", *p); // 5
printf("%d\n", **q); // 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 **.
c
void allocate(int **out) {
*out = malloc(sizeof(int));
**out = 7;
}
int main(void) {
int *q = NULL;
allocate(&q); // q now points to fresh memory
printf("%d\n", *q); // 7
free(q);
return 0;
}argv is a pointer to pointer
In main(int argc, char **argv), argv is 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...