C Memory Address
When a variable is created, the computer gives it a place in memory. That place has a number, its memory address, much like a house number on a street. Understanding addresses is the key to pointers, the next topic.
The address operator &
& in front of a variable gives its address. Print it with %p, which shows the number in hexadecimal. The value depends on the computer and changes between runs, so your output will differ from anyone else's.
#include <stdio.h>
int main(void) {
int age = 12;
double price = 9.5;
printf("age = %d, stored at %p\n", age, (void *)&age);
printf("price = %.1f, stored at %p\n", price, (void *)&price);
return 0;
}The cast to (void *) is what %p expects; it does not change the address.
You have used addresses already
scanf("%d", &age) gives scanf the address of age, so it can store the number there. That is why the & is needed: without it, scanf would receive the value and could not change the variable.
Arrays are side by side
The elements of an array are stored next to each other. The difference between the addresses of two neighbours is the size of one element:
#include <stdio.h>
int main(void) {
int numbers[3] = {10, 20, 30};
char *first = (char *)&numbers[0]; // look at the addresses byte by byte
char *second = (char *)&numbers[1];
printf("Distance between neighbours: %td bytes\n", second - first);
printf("sizeof(int): %zu bytes\n", sizeof(int));
return 0;
}Distance between neighbours: 4 bytes sizeof(int): 4 bytes
Subtracting two addresses gives the distance between them (a value of type ptrdiff_t, printed with %td). Converting them to char * first measures the distance in bytes, because a char is one byte. The name of an array, numbers, is itself the address of its first element. That fact connects arrays and pointers.
Why addresses matter
Addresses let a function change a variable that belongs to its caller, let you build data structures that grow while the program runs, and let large data be passed around without copying it. The next topic shows how to store an address in a variable: a pointer.
Practice exercises
- Print the addresses of three
intvariables. Are they close to each other? - Print the addresses of the elements of a
chararray of 4 elements. How far apart are they? - Print the value of
numbersand&numbers[0]with%pand compare them.