Addresses
Welcome to the lesson on pointers. Many people find pointers the hardest part of C, so this lesson goes slowly, one small step per exercise. It pays off: pointers let a function change your variables, and they show how arrays really work.
It all starts with memory. While a program runs, its variables are stored in the computer's memory. You can picture memory as a long row of numbered boxes, like the lockers in a school corridor. Each variable gets its own box, and the number of its box is the variable's address.
To get the address of a variable, write & before its name: &age means "the address of age". To print an address, use %p (p as in pointer), the same way you print a whole number with %d:
#include <stdio.h>
int main(void) {
int age = 15;
int score = 80;
printf("age: %d\n", age);
printf("Address of age: %p\n", &age);
printf("Address of score: %p\n", &score);
return 0;
}This prints:
age: 15
Address of age: 0xfffc
Address of score: 0xfff8Addresses are printed in the hexadecimal system (base 16). That's why they start with 0x and can have the letters a to f among the digits. You don't need to read them. On your own computer, the addresses would be much longer, such as 0x7ffd5e8c3a4c, and they could even change every time you run the program. Only two things matter: every variable has an address, and different variables have different addresses.
The two addresses differ by 4 because an int takes up 4 bytes of memory (a byte is the smallest unit of memory). You won't have to count bytes in this course: the computer does that for you.
The & before a variable has nothing to do with && from conditions. One & right before a name means "the address of".
Watch out for these mistakes:
- When you forget the
&, the compiler stops you.printf("%p\n", age);ends with the errorformat specifies type 'void *' but the argument has type 'int'.%pexpects an address (void *is how C writes "an address of anything"), butageis anint, the number 15. - The opposite mistake:
printf("%d\n", &age);ends with the errorformat specifies type 'int' but the argument has type 'int *'.%dexpects a whole number, but&ageis an address. The typeint *means "the address of anint". You'll meet it in the next exercise.
Instructions
At the end of the program (before return 0;), print the address of the variable lives: the text Address of lives: and %p with &lives. The program then also prints a line like Address of lives: 0xfffc (the number may be different).
Below it, print the address of coins the same way, with the text Address of coins: . The two addresses are different: each variable has its own box.
Start programming for free
1/11