Nearby lessons
88 of 124C - Pointer Declaration
How to declare a pointer in C — the type *name; syntax, why the asterisk binds to the name and not the type, pointers to every kind of data, and the special case of void *.
The Declaration Syntax
Write the target type, an asterisk, then the name. The three spacings below are identical to the compiler:
The Asterisk Binds to the Name
int* p;. The * belongs to the declarator, not the type. So int* a, b; declares one pointer and one plain int — which is almost never what the author intended. Writing int *a, *b; makes the truth visible.A Pointer for Every Type
Any type can be pointed to, including other pointers:
Types Must Match
Assigning the wrong pointer type is a warning at best and a silent misread at worst — the pointer type decides how many bytes are read:
void * — The Generic Pointer
A void * can hold the address of anything, which is why malloc returns one. It cannot be dereferenced until you cast it to a real type:
Pointers to Structs
Use -> to reach a member through a pointer. It is shorthand for (*p).member:
const and Pointers — Read It Backwards
Where you put const decides what is frozen. Read the declaration right to left:
| Declaration | Reads as | Can change *p? | Can change p? |
|---|---|---|---|
int *p | pointer to int | Yes | Yes |
const int *p | pointer to const int | No | Yes |
int *const p | const pointer to int | Yes | No |
const int *const p | const pointer to const int | No | No |
Function Pointers
A function has an address too. The parentheses around *name are essential — without them you declare a function returning a pointer:
Always Initialise
An uninitialised pointer holds garbage. Point it at something real, or at NULL so you can test it:
Common Mistakes
int* a, b;— onlyais a pointer. Writeint *a, *b;.- Declaring without initialising —
int *p;then*p = 5;is undefined behaviour. - Mismatched types —
int *p = &someChar;reads past the variable. - Dereferencing a
void *— cast it first. - Forgetting parentheses in a function pointer —
int *f(int)is a function, not a pointer. - Using
.instead of->on a struct pointer.
int *(*p)[5] is: p is a pointer, to an array of 5, of pointers to int. Start at the identifier, go right when you can, left when you must.- Syntax: type *name; — the type is what it points to.
- In int *a, *b; both are pointers; in int *a, b; b is a plain int.
- A pointer type must match what it points to.
- void * can hold any address but cannot be dereferenced directly.
- const placement decides what is protected — the pointer or the target.