Explain it simply
Explain it simply
Picture memory as a very long street of numbered lockers, one byte per locker. When you declare int age = 43;, the compiler reserves a few neighbouring lockers (four, on the PCs you are likely to use) and writes 43 into them. The number of the first locker is the variable's memory address.
In C you can ask for that number with the & operator: &age means "the address of age". You rarely care about the exact number. What matters is that an address lets other code find that same variable, which is how scanf() fills in your variables and how the pointers of the next lesson work.
Problem → Why → Solution
The problem: why scanf() breaks without &
In the User Input lesson you wrote scanf("%d", &age); and probably wondered what the & is for. Leave it out and the program still compiles, but it typically crashes as soon as you type a number, or, worse, silently writes the number somewhere else in memory. GCC with -Wall does warn you: format '%d' expects argument of type 'int *', but argument 2 has type 'int'.
#include <stdio.h>
int main(void) {
int age = 0;
printf("Enter your age: ");
scanf("%d", age); /* BUG: passes the value 0, not where age lives */
printf("You are %d\n", age);
return 0;
}Why does scanf() need an address?
C passes arguments by value, so scanf("%d", age) hands scanf a copy of the number currently inside age (here 0), not the variable itself. scanf has no way to put a result back into a copy. It needs to know where age lives so it can write the converted number into those exact bytes. Passing the value 0 makes scanf treat 0 as an address and write there, which is undefined behaviour.
Core concept: addresses, sizeof and layout
Every object in a running C program, whether a variable, an array or a struct, occupies a run of bytes in memory, and its address is the location of the first of those bytes. The unary & operator produces that address. If x has type int, then &x has type int * (read it as "pointer to int"), so the address carries type information along with the location: the compiler knows that the four bytes starting there hold an int.
sizeof is the companion of &. It tells you how many bytes an object or type occupies, as a value of type size_t, which printf prints with %zu. On today's 64-bit Windows and Linux PCs a char is 1 byte, an int is 4, a double is 8 and every pointer is 8. Only char is fixed at 1 by the standard; the others are whatever the compiler chose for the platform, so print sizeof instead of assuming.
To print an address, use the %p conversion and cast the pointer to (void *), because %p is defined for void * only. The output looks like 0x7ffe5367e044 on Linux, or 16 hex digits without 0x with GCC on Windows: both the format and the number are up to the implementation. Modern operating systems also randomize where the stack and heap start (address space layout randomization), so the same program usually prints a different address on every run. Treat a printed address as a debugging clue, never as data your program depends on.
What you can rely on is the layout inside a single array. Elements are stored next to each other with no gaps, so &scores[1] is exactly sizeof scores[0] bytes after &scores[0], and subtracting the addresses of two elements gives the number of elements between them. Separate variables are different: the compiler may place them in any order with any spacing, and ordering comparisons such as < between unrelated objects are not even defined by the standard.
int scores[3] = {70, 85, 92}; (int is 4 bytes)
-----------------------------------------------
byte offset: 0 4 8 12
+-------+-------+-------+
| 70 | 85 | 92 |
+-------+-------+-------+
^ ^ ^
&scores[0] &scores[1] &scores[2]
(char *)&scores[1] - (char *)&scores[0] -> 4 (bytes)
&scores[2] - &scores[0] -> 2 (elements)- Declaring reserves a run of bytes
- &name gives the first byte's address
- sizeof says how many bytes it spans
- The address is valid while it lives
Rely on distances inside one array, never on the exact number %p prints.
General pattern
type name = value;
type *where = &name; /* address of name; its type is type * */
printf("%p\n", (void *)&name); /* print an address (varies per run) */
printf("%zu\n", sizeof name); /* bytes the object occupies */
ptrdiff_t gap = &arr[j] - &arr[i]; /* elements between two items, use %td */& gives an address whose type is a pointer to the variable's type. %p prints it after a (void *) cast, %zu prints a sizeof result, and subtracting two element addresses of the same array gives a ptrdiff_t, printed with %td.
Example: exploring memory without printing raw addresses
This program never prints a raw address, so its output is the same on every run and on every 64-bit PC. Instead it shows the facts you can rely on: how big each object is, that &age really identifies age, and how far apart the array elements sit.
On a platform where int is 2 bytes, such as some microcontrollers, the byte counts would change, but the element distance of 2 would not.
#include <stdio.h>
int main(void) {
int age = 43;
int scores[3] = {70, 85, 92};
printf("age = %d, stored in %zu bytes\n", age, sizeof age);
printf("scores uses %zu bytes for 3 ints\n", sizeof scores);
/* &age means "the address of age"; its type is int * */
int *where = &age;
printf("where holds the address of age: %s\n", where == &age ? "yes" : "no");
/* Array elements sit side by side, so distances are predictable */
char *first = (char *)&scores[0];
char *second = (char *)&scores[1];
printf("bytes from scores[0] to scores[1]: %td\n", second - first);
printf("elements from scores[0] to scores[2]: %td\n", &scores[2] - &scores[0]);
return 0;
}Code breakdown
- Line 7
sizeof ageThis is 4 on 64-bit Windows and Linux. The result is a size_t, so the matching printf conversion is %zu.
- Line 8
sizeof scoresOn an array, sizeof measures the whole array: 3 elements times 4 bytes is 12. This only works where the array itself is in scope, not on a pointer to it.
- Line 11
int *where = &age;&age produces the address of age, and storing it needs a variable of type int *. The next lesson is all about such variables.
- Line 12
where == &ageComparing two addresses with == is always allowed and tells you whether they name the same object. It prints yes without ever showing the number.
- Lines 15-17
(char *)&scores[1]Casting to char * makes the subtraction count bytes, because a char is one byte. The result is 4, the size of one int.
- Line 18
&scores[2] - &scores[0]Subtracting two int addresses counts elements, not bytes, so the answer is 2. The result type is ptrdiff_t, printed with %td.
age = 43, stored in 4 bytes
scores uses 12 bytes for 3 ints
where holds the address of age: yes
bytes from scores[0] to scores[1]: 4
elements from scores[0] to scores[2]: 2Looking at a real address with %p
When you really want to see an address while debugging, use %p. Run the program below twice and compare the output. The sample output after it comes from GCC on Windows; your numbers will be different, and that is normal.
#include <stdio.h>
int main(void) {
int age = 43;
double price = 9.99;
printf("age lives at %p\n", (void *)&age);
printf("price lives at %p\n", (void *)&price);
return 0;
}age lives at 000000f02a9ffa6c
price lives at 000000f02a9ffa60
age lives at 000000b7f37ff7ac
price lives at 000000b7f37ff7a0You may notice that price sat 12 bytes below age in both runs. That is simply the layout this compiler chose with these options, not a promise: compiling with -O2 or switching compilers can change the order too.
Lifetime: when an address stops being valid
An address is only useful while the object it names is alive. In C, three storage durations decide how long an object lives.
| Kind of object | Lives until |
|---|---|
| Local variable inside a function (automatic) | The end of the block { } that declares it |
| Global variable or static local (static) | The whole run of the program |
| Memory from malloc() (allocated) | free() is called (Dynamic Memory lesson) |
As soon as a function returns, the memory of its local variables is reused by later calls. Returning the address of a local therefore leaves the caller holding the number of a locker nobody owns any more. GCC flags such code with function returns address of local variable [-Wreturn-local-addr]. When data must outlive the call, return the value itself, accept the address of a variable the caller owns, or use malloc().
In real projects
Where this shows up in real projects
You meet addresses long before you write pointer-heavy code. Every scanf() call, every function that fills in a result through a parameter (such as the standard strtol() with its end pointer) and every array passed to a function works with addresses under the hood. Debuggers such as gdb and the Visual Studio debugger show addresses next to variables, so you can tell whether two names refer to the same object.
Printing addresses is a diagnostic tool. When a program crashes, tools like AddressSanitizer (-fsanitize=address in GCC and Clang, for example on Linux, and also available in recent MSVC versions) report the faulty address together with where that memory was allocated and freed. Logging %p values can reveal that two structures share one buffer, but production code should never store or compare printed address strings, because they change on every run.
Common mistakes
Common mistakes
1. Printing an address with %d or %x
On a 64-bit PC an address is 8 bytes while an int is 4. printf("%d", &n) is undefined behaviour and in practice prints a truncated, meaningless number. GCC warns: format '%d' expects argument of type 'int', but argument 2 has type 'int *'. Use %p with a (void *) cast.
2. Reading meaning into the order of variables
If price happens to sit 12 bytes below age in one build, another compiler, optimization level or platform may lay them out differently. Only addresses inside the same array (or the same struct) have a guaranteed relationship.
3. Keeping a local's address after its function returns
A function like int *make_counter(void) { int count = 0; return &count; } hands back the address of memory that is released the moment the function ends. Using that address is undefined behaviour: it may appear to work and then fail after an unrelated change. Treat the -Wreturn-local-addr warning as an error.
Best practices
Best practices
- Compile with -Wall -Wextra so format and argument mismatches involving addresses are reported.
- Use sizeof instead of hard-coding sizes such as 4 or 8.
- Use addresses for identity checks (==) and for distances inside one array, not for ordering unrelated variables.
Mini challenge
Mini challenge: map three arrays
Write a program that reports how three small arrays are laid out in memory, using sizes and distances instead of raw addresses.
- Declare a char[4], an int[4] and a double[4] array
- Write a report() helper that prints a label, the element size, the whole array size and the byte distance from element 0 to element 3
- Compute the byte distance by casting the element addresses to char * and subtracting
- Finally print the element distance &counts[3] - &counts[0] for the int array
#include <stddef.h>
#include <stdio.h>
static void report(const char *label, size_t element, size_t total, ptrdiff_t span) {
// TODO: print one aligned line, e.g. "int : element 4, array 16, ..."
}
int main(void) {
// TODO: declare char letters[4], int counts[4] and double prices[4]
// TODO: call report() once per array: sizes come from sizeof,
// the span from (char *)&arr[3] - (char *)&arr[0]
// TODO: print &counts[3] - &counts[0] with %td
return 0;
}Expected: On a 64-bit Windows or Linux PC: char : element 1, array 4, [0] to [3] = 3 bytes int : element 4, array 16, [0] to [3] = 12 bytes double: element 8, array 32, [0] to [3] = 24 bytes &counts[3] - &counts[0] = 3 elements
Show hint
sizeof letters[0] is the size of one element and sizeof letters is the whole array. For the span, (char *)&letters[3] - (char *)&letters[0] counts bytes because a char is one byte. Print a ptrdiff_t with %td and a size_t with %zu; %-6s lines up the labels.
Show solution
#include <stddef.h>
#include <stdio.h>
static void report(const char *label, size_t element, size_t total, ptrdiff_t span) {
printf("%-6s: element %zu, array %zu, [0] to [3] = %td bytes\n",
label, element, total, span);
}
int main(void) {
char letters[4] = {'a', 'b', 'c', 'd'};
int counts[4] = {1, 2, 3, 4};
double prices[4] = {1.5, 2.5, 3.5, 4.5};
report("char", sizeof letters[0], sizeof letters,
(char *)&letters[3] - (char *)&letters[0]);
report("int", sizeof counts[0], sizeof counts,
(char *)&counts[3] - (char *)&counts[0]);
report("double", sizeof prices[0], sizeof prices,
(char *)&prices[3] - (char *)&prices[0]);
printf("&counts[3] - &counts[0] = %td elements\n", &counts[3] - &counts[0]);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- &x gives the address of x, and its type is a pointer to x's type (int * for an int).
- sizeof reports how many bytes an object occupies; print it with %zu instead of assuming sizes.
- Print addresses only for debugging, with %p and a (void *) cast; the number changes between runs and platforms.
- Within one array, addresses are evenly spaced, so differences between element addresses are reliable.
- An address is only usable while its object is alive; never keep a local's address after its function returns.
SEI CERT C Coding Standard — Carnegie Mellon SEI