Codiqo

Learn C · lesson 33 of 60 · about 8 minutes

Addresses and Pointers

Let the admin adjust a figure in the report: learn what a pointer is, and read and write a variable through one with & and *.

What you'll learn

  • Explain what an address is
  • Declare a pointer
  • Use & to take an address and * to follow it

Adjusting a figure

At the end of the report, the admin can correct one figure: they type its name and an amount, like free 300. The report makes int *figure = NULL; and points it at whichever variable was named: figure = &free_kib;. Then one line, *figure += amount;, changes that variable, whichever it is, because figure holds its address. If the name doesn't match any figure, figure stays NULL, and the report checks for that before following it.

Every variable lives somewhere

Memory is a long row of numbered bytes. The number of a variable's first byte is its address.

  • &x means "the address of x"
  • A pointer is a variable that stores an address: int *p = &x; means "p points to an int, namely x"
  • *p means "the value p points to" (following the pointer is called dereferencing)

Reading and writing through a pointer

#include <stdio.h>

int main(void) {
    int coins = 50;
    int *p = &coins;

    printf("coins is %d\n", coins);
    printf("*p is %d\n", *p);
    *p = 75;
    printf("coins is now %d\n", coins);
    printf("p points to coins: %d\n", p == &coins);
    return 0;
}

Output

coins is 50
*p is 50
coins is now 75
p points to coins: 1

Pointing nowhere

NULL is a special address meaning "points to nothing". Following a NULL pointer crashes the program, so check if (p != NULL) before using a pointer that might be empty.

Tip

The * means two different things: in a declaration (int *p) it says "p is a pointer"; in an expression (*p) it says "follow p".

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.