Nearby lessons
86 of 124C - Memory Address
Every variable lives at a numbered location in memory. Learn what a memory address is, how the & operator reveals it, how to print one with %p, and how addresses relate to a variable's size.
Memory Is a Numbered Row of Bytes
Think of RAM as a very long street where every byte has a house number. When you declare int x = 42; the compiler reserves a few consecutive bytes and remembers the number of the first one.
| Address | Contents | Belongs to |
|---|---|---|
| 0x7ffd1000 | 42 | int x (4 bytes) |
| 0x7ffd1004 | 'A' | char c (1 byte) |
| 0x7ffd1008 | 3.14 | float f (4 bytes) |
The & Address-Of Operator
Put & in front of a variable to get its address instead of its value:
Printing Addresses with %p
%p is the correct specifier for an address, and the standard expects a void * — so cast. Using %d instead is wrong and may print garbage on 64-bit systems:
Size Determines the Spacing
Declare an array and the addresses step forward by exactly sizeof(element) each time — proof that memory is contiguous:
Different Types, Different Steps
A char array steps by 1, a double array by 8. The type is what tells C how far to move:
Addresses Change Every Run
Modern operating systems randomise where your program's memory lands, for security. Run the same program twice and you will see different numbers:
Where Different Variables Live
Globals, locals and heap allocations sit in distinct regions, and their addresses reflect that:
Why scanf Needs the &
This is the first place every C learner meets addresses. scanf must write into your variable, so it needs to know where the variable is — not what it currently holds:
Comparing Addresses
Addresses are numbers, so you can compare them. Within one array this is well-defined and genuinely useful:
Common Mistakes
- Forgetting
&inscanf—scanf("%d", age)treats the value as an address and corrupts memory. - Adding
&to an array inscanf— an array name already is an address. - Printing with
%d— use%pwith a(void *)cast. - Hard-coding an address — they change every run.
- Taking the address of a literal —
&5is meaningless; only objects have addresses. - Keeping the address of a local after its function returns — the storage is gone.
scanf("%d", age) is the classic. If age happens to hold 42, scanf writes an integer to address 42 — memory your program does not own. It crashes immediately, or worse, appears to work. Build with -Wall and the compiler will flag the format mismatch every time.- Memory is a numbered sequence of bytes; an address is one of those numbers.
- &variable gives the address of variable.
- Print an address with %p and a (void *) cast.
- A variable occupies sizeof(type) consecutive bytes.
- Addresses change between runs — never hard-code one.