What Is a Pointer?
An address, & to get it, * to follow it.
6 minute read
Big idea
A pointer is a variable that stores an address — where another variable lives in memory. & gets an address; * follows one.
The idea
Every variable sits somewhere in memory, and every spot in memory has a numbered address. You've already used one: scanf("%d", &age) hands scanf the address of age.
int score = 90;
int *p = &score;
int *p—pis a pointer to an int: it holds the address of anint.&score— "the address ofscore".- Now
ppoints toscore.
Follow the pointer with *:
printf("%d\n", *p); // 90 — the value at the address in p
*p = 95; // changes score, through the pointer
Watch it
(Real addresses are longer and change every run — these are shortened to read easily.)
Watch a pointer move
See real addresses
%p prints an address. Run it twice — the numbers change, but &x and p always match:
#include <stdio.h>
int main(void) {
int x = 7;
int *p = &x;
printf("&x = %p\n", (void *) &x);
printf("p = %p\n", (void *) p);
printf("*p = %d\n", *p);
return 0;
}Run and edit it in the app.
The two meanings of *
- In a declaration,
*makes a pointer type:int *p; - In an expression,
*follows the pointer:*p = 5;
Common mistake
Using a pointer before pointing it anywhere. An uninitialised pointer holds a random address; writing through it can crash or silently corrupt other data. Point it at something first — or set it to NULL (address zero, "points nowhere") and check before use:
int *p = NULL;
if (p != NULL) {
*p = 5;
}
After int a = 4; int *p = &a; *p = *p * 3; what is a?
Think of it like
A contact card with someone's home address. The card isn't the house — but by following the address you can visit the house and even repaint the door.
🕷️ Spidey-sense: My spider-tracer doesn't hold the villain — it holds where the villain is. Follow the tracer (
*), and I'm right there. Pointers: with great power comes great responsibility.
Key terms
- Address — The location of a variable in memory.
- Pointer — A variable holding an address.
&(address-of) — Gets a variable's address.*(dereference) — Follows a pointer to the value it points at.- NULL — A pointer that points nowhere.
Check yourself
What does &x give?
If p = &x, what is *p?
What is a safe value for a pointer that points nowhere yet?