Step 1 of 10
Addresses and pointers
Pointers are the idea that makes C, C. They're also the topic most beginners find hardest, so take this module slowly and use the Watch it run links: seeing the arrows helps enormously.
Memory is a long row of numbered bytes
Your computer's memory is like a very long street of mailboxes, each holding one byte and each with a number: its address. When you declare int hp = 100;, the compiler reserves 4 bytes somewhere on that street for hp. The variable's name is for you; the machine only knows the address.
The & operator gives you a variable's address: &hp means "where hp lives". You've already used it with scanf.
A pointer is a variable that holds an address
#include <stdio.h>
int main(void) {
int hp = 100;
int *p = &hp;
printf("%d\n", *p);
*p = 75;
printf("%d\n", hp);
hp = 20;
printf("%d\n", *p);
return 0;
}
100
75
20
int *pdeclarespas a pointer to int: a variable whose value is the address of an int.p = &hpstoreshp's address inp. We say "ppoints athp".*pdereferences the pointer: it means "the int at the address stored inp". Reading*preadshp; writing*p = 75writes intohp.
p and hp are two separate variables. Changing hp is visible through *p, and changing *p changes hp, because they refer to the same memory.
Two meanings of *
In a declaration (int *p), * means "p is a pointer". In an expression (*p = 75), * means "follow the pointer". Same symbol, two jobs; it's the main thing that makes pointer code look confusing at first.
(The actual numbers stored in pointers vary from run to run and machine to machine, so you rarely print them. You can with %p if you're curious.)
Your turn: make p point at armor, then use p (not armor directly) to set it to 50.