3.5Pointers to pointers
The idea
A pointer to pointer (char **) stores the address of another pointer, which lets a function change the caller's pointer.
Think of it like this: To change a friend's phone number in their contacts you need their contacts page itself, not a photocopy of the number.
Why it exists
Swap questions test whether you know that only the address of the pointer lets you modify it.
How it works
- A function receives copies of its arguments.
- Copies of pointers can still reach the pointed-to data, but reassigning the copy has no effect outside.
- To change the caller's pointer, pass &ptr (a pointer to the pointer) and assign *param.
Worked example: fun1(str1, str2) versus fun2(&str1, &str2)
fun1 swaps two local copies: nothing changes, printing Hi Bye. fun2 swaps the pointers themselves, so str1 now points to "Bye": Bye Hi.
Now play with it
- →Run the swap pointers program and watch str1 and str2 only change after fun2.
- →Step into fun1 and see s1 and s2 swap while str1 and str2 stay put.
fun1 swaps its own COPIES of the two pointers, so main sees no change. fun2 receives the ADDRESSES of the pointers (char **), so swapping through them changes the caller's pointers.
1#include <stdio.h>2void fun1(char *s1, char *s2) {3 char *tmp;4 tmp = s1; s1 = s2; s2 = tmp;5}6void fun2(char **s1, char **s2) {7 char *tmp;8 tmp = *s1; *s1 = *s2; *s2 = tmp;9}10int main() {11 char *str1 = "Hi", *str2 = "Bye";12 fun1(str1, str2);13 printf("%s %s ", str1, str2);14 fun2(&str1, &str2);15 printf("%s %s\n", str1, str2);16 return 0;17}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
To make a function change which string a caller's char *s points to, the parameter must be
Exam notes (the dense version)
A char ** holds the address of a char *. A function that must change the caller's pointer takes a pointer to it, as in swap(char **a, char **b). Swapping two local copies of pointers does nothing in the caller. argv is a char ** (array of strings).
Previous year questions: Pointers & Arrays (11)
PYQs are grouped by topic, so this is the full set for Pointers & Arrays; try the ones that match this subtopic. Open all 11 on the topic page.