A pointer has its own address, so another pointer can store that address. int **q means q points to an int *; *q reaches p, and **q follows p to data.
#include <stdio.h>
int main(void) {
int data = 5;
int *p = &data;
int **q = &p;
printf("%d\n", data);
printf("%d\n", *p);
printf("%d\n", **q);
return 0;
}KNOWLEDGE QUIZ
QUESTION
What is the type of *q?
INTERACTIVE LAB
Read and write through an address chain
ACCESSPRO
PRO EXCLUSIVEGo further with Pro
Unlock Pro accessUnlock the complete interactive lab, deeper explanations, and curated reference answers.
Changing a pointer variable itself
Passing an int ** lets a function change the caller's pointer variable, not merely the final integer. Pass the pointer's address, as in redirect(&p, &other).
void redirect(int **target, int *destination) {
*target = destination;
}KNOWLEDGE QUIZ
QUESTION
Which object is changed by **q = 9?
KNOWLEDGE QUIZ
QUESTION
What should a function receive to change caller pointer p?
HANDS-ON PRACTICE
Redirect a pointer
Implement choose_larger(int **selected, int *a, int *b) so selected points to the larger integer. Test with 4 and 9, then print 9 through **selected.
- Initially point p at first in main.
- Accept int **target and a replacement int *.
- Assign *target = replacement and verify the caller's *p.