Sub topic 10
Pointers to pointers
This chapter assumes you can declare a pointer, take an address with &, dereference with *, and write a function that takes a pointer argument. It also assumes you know that arrays decay to pointers and that malloc returns a heap address. If any of these are shaky, review the earlier chapters on pointer basics and pass by value first.
What a pointer to pointer is
A pointer is a variable that stores an address. Since a pointer is itself a variable, it has an address too. A pointer to pointer stores that address. Its type has two stars, as in int **pp.
#include <stdio.h>
int main(void) {
int x = 5;
int *p = &x;
int **pp = &p;
**pp = 7;
printf("%d %d\n", x, **pp);
int y = 9;
*pp = &y;
printf("%d\n", *p);
printf("%d\n", x);
return 0;
}The output is 7 7, then 9, then 7. The statement **pp = 7 follows two arrows to reach x. The statement *pp = &y writes into p itself, so p now points at y. The variable x is untouched.
Each dereference removes one star from the type:
| Expression | Type | Meaning |
|---|---|---|
| `pp` | `int **` | address of `p` |
| `*pp` | `int *` | the value stored in `p` (address of `x`) |
| `**pp` | `int` | the value stored in `x` |
| `&pp` | `int ***` | address of `pp` itself |
For GATE questions, write the type of every subexpression like this. A mismatch between the stars on the left and right of an assignment is the usual sign that you misread the code.
Why you need it: changing a caller's pointer
C passes arguments by value. A function that receives int *q gets a copy of the pointer, so assigning to q changes only the copy. To change the caller's pointer, pass its address, which has type int **.
#include <stdio.h>
#include <stdlib.h>
void make_bad(int *q) {
q = malloc(sizeof *q);
if (q != NULL) {
*q = 42;
}
}
int make_good(int **q) {
*q = malloc(sizeof **q);
if (*q == NULL) {
return -1;
}
**q = 42;
return 0;
}
int main(void) {
int *p = NULL;
make_bad(p);
printf(p == NULL ? "still NULL\n" : "set\n");
if (make_good(&p) == 0) {
printf("%d\n", *p);
free(p);
}
return 0;
}The program prints still NULL, then 42. make_bad also leaks its allocation, because the only pointer to that block disappears when the function returns. Note the idiom sizeof **q. It gives the size of an int and stays correct if the pointed-to type changes.
Linked lists: the head pointer problem
Inserting at the front of a list changes the head pointer, so the function needs the address of the head. This is the most common real use of struct node **.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void push(struct node **head, int v) {
struct node *n = malloc(sizeof *n);
if (n == NULL) {
return;
}
n->data = v;
n->next = *head;
*head = n;
}
void remove_value(struct node **head, int v) {
struct node **pp = head;
while (*pp != NULL && (*pp)->data != v) {
pp = &(*pp)->next;
}
if (*pp != NULL) {
struct node *t = *pp;
*pp = t->next;
free(t);
}
}
int main(void) {
struct node *head = NULL;
for (int i = 1; i <= 3; i++) {
push(&head, i);
}
remove_value(&head, 2);
for (struct node *c = head; c != NULL; c = c->next) {
printf("%d ", c->data);
}
printf("\n");
while (head != NULL) {
struct node *t = head->next;
free(head);
head = t;
}
return 0;
}The program prints 3 1. In remove_value, the variable pp points at the pointer that leads to the current node. That pointer is either head or some node's next field. Because pp points at the link rather than at the node, removing the first node needs no special case: *pp = t->next works for every position. The expression &(*pp)->next parses as &((*pp)->next), because -> binds tighter than unary &.
Arrays of pointers and `char **`
An array of pointers decays to a pointer to its first element. That element is a pointer, so the decayed type has two stars. This is why main can take char **argv.
#include <stdio.h>
int main(void) {
const char *names[] = {"red", "green", "blue"};
const char **q = names;
printf("%s %c\n", *(q + 1), q[2][0]);
printf("%c\n", **q);
q++;
printf("%s\n", *q);
return 0;
}The output is green b, then r, then green. Adding 1 to q moves it by sizeof(const char *), not by one char. Pointer arithmetic always scales by the size of the pointed-to type. For int **pp, pp + 1 advances by sizeof(int *), while *pp + 1 advances by sizeof(int).
Not the same as a 2D array
A malloced table built as int **m is a separate array of row pointers. Each row is a separate allocation and may sit anywhere in memory. A true int a[2][3] is one contiguous block. The two are different types, and the compiler uses different address calculations for them.
If you build a table with int **m, you must free it in two steps. Free each row first, then free the row-pointer array. Freeing only m leaks every row. Freeing m first loses the row addresses.
Common errors
- Writing
*pp = malloc(...)whenpphas never been set to point at a valid pointer. Dereferencing an uninitialized orNULLppis undefined behavior. - Passing
pwhere&pis needed, as inmake_bad(p)above. The code compiles, but the caller's pointer never changes. - Assigning
char **toconst char **. C does not convert this implicitly, because it could let you modify aconstobject through a back door. Declare the pointers with matchingconstlevels. - Counting stars wrongly in a trace. After each statement, list what every variable holds: an address, an int, or
NULL.
Exercise
What do a, b, and *p hold after this code runs? Print them in that order.
int a = 1, b = 2;
int p = &a, q = &b;
int pp = &p;
pp += 10;
pp = q;
*pp += 5;
Show answer
11 7 7. The first **pp += 10 follows pp to p to a, so a becomes 11. Then *pp = q makes p point at b. The second **pp += 5 now follows pp to p to b, so b becomes 7, and *p is also b, which is 7.
Exercise
On a typical 64-bit system, where sizeof(int) is 4 and sizeof(int *) is 8, int **pp holds address 1000. What address does pp + 1 hold? What would *pp + 1 add, if *pp held 2000?
Show answer
pp + 1 is 1008, because pp points to an int * and the step is sizeof(int *), which is 8. *pp + 1 is of type int * and adds sizeof(int), which is 4, so it gives 2004.