Pointers
Challenge Gallery
Quick Reference
Pointer operations:
| Operation | Syntax | Meaning |
|---|---|---|
| Declare | int *p; |
p is a pointer to int |
| Address-of | p = &x; |
p now holds x’s address |
| Dereference | *p |
Follow p to access the value |
| Write through | *p = 42; |
Write 42 to where p points |
| NULL check | if (p != NULL) |
Verify before dereferencing |
| Print address | printf("%p", (void *)p) |
Show the hex address |
The mental model:
Variable Address Value
┌──────┐
│ x │ 0x1000 → [ 42 ]
└──────┘
┌──────┐
│ p │ 0x1008 → [0x1000] ──→ points to x
└──────┘
*p reads/writes the value at 0x1000 (which is x)
Declaration vs. dereference:
| Context | * means |
Example |
|---|---|---|
| Declaration | “pointer to” | int *p; → p is a pointer to int |
Expression (right of =) |
“read through” | y = *p; → read what p points to |
Expression (left of =) |
“write through” | *p = 42; → write to where p points |
Common Pitfalls
- Uninitialized pointers —
int *p; *p = 42;writes to a garbage address. Always initialize to&variableorNULL. - Dangling pointers — After
free(p), p still holds the old address. Setp = NULLimmediately. - Forgetting
&in scanf —scanf("%d", x)passes the value of x, not its address. Usescanf("%d", &x). - Confusing
*in declarations vs. expressions —int *pdeclares a pointer.*pin code dereferences it. Same symbol, different meaning. ==on pointers — Compares addresses, not values.p == qchecks if they point to the same location, not if the pointed-to values are equal.