🚀 Alguni Start learning

Unit 4: Pointers, Gently

The famous scary bit.

Unit 4 of 11 in C programming for kids. Its 3 lessons are Every Box Has an Address, Pointers and Pointer Master — below is everything each one explains, and a question or two from it to try.

Every sample on this page was compiled and run with gcc before it shipped, and prints exactly what it says it prints.

This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.

📮 Every Box Has an Address

Houses have numbers

Every variable lives somewhere in memory, and that somewhere has a number — its address, like a house number on a street. &score means "the address of score", not the value inside it.

C

int score = 10;
printf("%d\n", score);   // the value:   10
printf("%p\n", &score);  // the address: 0x7ffd...

Why bother?

Because an address is small and a thing can be huge. Handing a function an address instead of a copy is cheap — and it lets that function change your original, instead of scribbling on a copy and throwing it away.

Try it yourself

What does &score mean?

  • The value inside score
  • The address where score lives
  • score doubled
  • A comment

Why can nobody predict what an address will be?

  • C picks a random number for fun
  • It depends where the computer happened to put the variable this time
  • Addresses are always 0
  • It is a secret

Answer them in the app

👉 Pointers

A box that holds an address

A pointer is a variable that holds an address. The * in int *p says "p points at an int". Later, *p means "go to that address and get the value" — people call it *following* the pointer.

C

int score = 10;
int *p = &score;
printf("%d\n", *p);

It prints

10

Changing things from a distance

Follow a pointer and you can change the original variable — without ever mentioning its name.

C

int n = 7;
int *p = &n;
*p = 99;
printf("%d\n", n);

It prints

99

Try it yourself

In int *p = &score;, what goes into p?

  • 10
  • The address of score
  • A copy of score
  • Nothing

What does this print?

C

int n = 7;
int *p = &n;
printf("%d\n", *p);

Answer them in the app

🏆 Pointer Master

The classic C party trick

Pass a pointer into a function and the function can change your variable for real. Pass a plain copy and it cannot — it only ever scribbles on the copy.

C

void set_to_five(int *n) {
    *n = 5;
}

int main() {
    int score = 0;
    set_to_five(&score);
    printf("%d\n", score);
    return 0;
}

It prints

5

Try it yourself

What does this print?

C

int x = 3;
int *p = &x;
*p = *p * 10;
printf("%d\n", x);

And what about this one? (No pointer this time!)

C

void set_to_five(int n) {
    n = 5;
}

int main() {
    int score = 0;
    set_to_five(score);
    printf("%d\n", score);
    return 0;
}

Answer them in the app