Brainlag
  1. Library
  2. Concepts
  3. C

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.

C10 min

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.

Memory, step by step
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.

main.c to run
#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

  1. Heals the real variable
  2. Never above 100
exercise_1.c to run
void heal(int *hp, int amount) {
    ___
}

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.