Pointers and addresses
Every variable lives at an address. A pointer is a variable that holds one, and * follows it to the value that lives there.
Every value has an address
Memory is one long row of numbered bytes. An int takes four of them, and the number of the first one is its address. &x asks "where does x live?". A pointer is a variable that stores an address, and *p means "go to that address and use what is there". Step through it.
int hp = 100; int *p = &hp; *p = 70; int shield = 5; p = &shield; *p = *p * 2;
The addresses here are made up but realistic: on this site's compiler an int and a pointer are both 4 bytes, so neighbours sit 4 apart.
The two stars
int *p in a declaration means "p is a pointer to an int". *p anywhere else means "the int that p points at". Same symbol, two jobs. p alone is the address; *p is the value.
Run it: change a value through a pointer
Run it, then change one thing and run it again.
#include <stdio.h>
int main(void) {
int hp = 100;
int *p = &hp;
printf("hp lives at %p\n", (void *)&hp);
printf("p holds %p\n", (void *)p);
*p = 70;
printf("hp is now %d\n", hp);
printf("a pointer here is %d bytes\n", (int)sizeof p);
return 0;
}
Heal through a pointer
Finish heal so it adds amount to the int that hp points at, but never above 100.
Checks
- Heals the real variable
- Never above 100
void heal(int *hp, int amount) {
___
}