Sub topic 10
Pointers to Pointers and Complex Declarations
Assume you know basic C syntax, functions, arrays, and how to compile a small C program. This chapter focuses on the working model used to trace pointers and declarations in GATE-style questions.
Pointers to pointers
A pointer stores the address of an object. A pointer to a pointer stores the address of a pointer.
int x = 10;
int *p = &x;
int **pp = &p;The three expressions refer to different objects:
xis anintwith value10.pis anint *containing the address ofx.ppis anint **containing the address ofp.*pgivesx.*ppgivesp.**ppgivesx.
Because pp can reach p, assigning through *pp changes the pointer p itself.
#include <stdio.h>
void point_to(int **p, int *target) {
*p = target;
}
int add(int a, int b) {
return a + b;
}
int main(void) {
int x = 10;
int y = 20;
int *p = &x;
int **pp = &p;
printf("%d\n", **pp);
point_to(&p, &y);
printf("%d\n", *p);
int (*fp)(int, int) = add;
printf("%d\n", fp(4, 5));
return 0;
}The output is:
10
20
9point_to receives the address of p, so it can change where p points. Passing only p would pass a copy of the pointer and would not change the caller's pointer.
Reading complex declarations and function pointers
Read a declaration from the identifier outward. Parentheses matter because postfix operators such as [] and () bind more tightly than *.
| Declaration | Meaning |
|---|---|
| `int *p` | `p` is a pointer to `int` |
| `int *a[3]` | `a` is an array of three pointers to `int` |
| `int (*a)[3]` | `a` is a pointer to an array of three `int` values |
| `int (*fp)(int, int)` | `fp` is a pointer to a function taking two `int` values and returning `int` |
A function pointer can store the address of a compatible function. Calling fp(4, 5) invokes the function stored in fp. The parameter types and return type must match.
Common errors include confusing int ** with a two-element integer array, forgetting parentheses around *a or *fp, and dereferencing an uninitialized pointer. Every pointer must point to a valid object before it is dereferenced.
Exercise
If int *a[3] and int (*b)[3] are declared, which one represents an array of pointers and which one represents a pointer to an array?
Show answer
a is an array of three pointers to int. b is a pointer to an array of three int values.