Pointer to pointer
- C course
- Intermediate
- Lesson 1/116
- 5 min
Learn the double pointer (**) concept.
Double pointer
A pointer to pointer holds the address of another pointer. In C it is declared with two stars (**).
Example: int x = 5; int *p = &x; int **pp = &p;. Here p holds the address of x; pp holds the address of p. *pp gives you p (the address of x); **pp gives you x itself. Two levels of indirection are thus achieved.
Modifying values via a double pointer
The most powerful use of a double pointer is changing the original variable from inside another function. Writing **pp = 42; changes the value of x directly.
This is like a single pointer modifying a variable; you are one level further out. *pp gives you p; **pp accesses x itself. That is why double pointers appear often in dynamic array allocation and tree data structures.
Practice Change a value through a double pointer
Declare a variable int x = 5;. Set up a double pointer with int *p = &x; and int **pp = &p;. Through **pp set x to 42 and print x with printf.
Starter code
#include <stdio.h>
// Declare x, p and pp
// Set x to 42 through **pp
// Print x
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int x = 5;
int *p = &x;
int **pp = &p;
**pp = 42;
printf("%d\n", x);
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which declares a pointer to pointer to int?
- int (*pp)*;
- int *pp[];
- int pp**;
- int **pp; Correct answer
Explanation: int **pp; says pp is a pointer to int*.
2 Access x through double indirection
int x = 5;
int *p = &x;
int **pp = &p;
printf("%d\n", ____);
int x = 5;
int *p = &x;
int **pp = &p;
printf("%d\n", **pp);
Explanation: **pp dereferences twice and yields the value of x.
3 Match the double pointer parts
| Term | Meaning |
|---|---|
int *p |
Single pointer |
int **pp |
Double pointer |
*pp |
value of p |
**pp |
value of x |