Nearby lessons
87 of 124C - Pointer Introduction
A pointer is a variable that stores a memory address. Learn what pointers are, the two operators & and * that make them work, and why C would be a far weaker language without them.
A Variable That Holds an Address
An ordinary variable holds data. A pointer holds the location of data:
| Declaration | Stores | Example content |
|---|---|---|
int x = 42; | The number 42 | 42 |
int *p = &x; | Where x lives | 0x7ffd1000 |
The Two Operators
& asks "where does this live?" and gives you an address. * asks "what is at this address?" and gives you the value. They are exact opposites, and *&x is just x.Writing Through a Pointer
*p is not read-only. Assign to it and you change the original variable — this is what makes pointers powerful:
The Pointer Type Matters
int *, char * and double * all store an address of the same size. The type tells C how many bytes to read and how to interpret them:
Why C Needs Pointers
Five things you simply cannot do in C without them:
| Need | Why a pointer is required |
|---|---|
| Modify a caller's variable | Arguments are copies; an address is not |
| Return several values | return sends back only one |
| Dynamic memory | malloc hands back an address |
| Efficient large data | Pass 8 bytes instead of copying a big struct |
| Linked lists and trees | Nodes must reference other nodes |
You Have Been Using Pointers All Along
scanf, array names and string functions are all pointer-based. Pointers were there from your first program:
Two Pointers to One Variable
Nothing stops several pointers from referring to the same location. All of them see every change:
Common Mistakes
- Dereferencing an uninitialised pointer —
int *p; *p = 5;writes to a random address. - Assigning a value instead of an address —
int *p = 42;makes 42 the address. - Confusing
pwith*p— one is the address, the other is the value. - Mismatched pointer types —
int *p = &someChar;reads 4 bytes where only 1 belongs. - Keeping a pointer to a dead local — a dangling pointer.
int *p; *p = 5; compiles without complaint and then writes 5 to whatever garbage address happened to be in p. Initialise at declaration — either to a real address or to NULL, then check before use.- A pointer holds an address, not a value.
- & takes an address; * follows one (dereference).
- Every pointer has a type that tells C how to read the target.
- All pointers are the same size regardless of what they point to.
- Pointers enable output parameters, dynamic memory and data structures.