Lesson 1 of 3 · Pointers · 3 min read · Updated

What a pointer actually is

Not magic, not hard — just a variable holding an address. Start here and the rest follows.

Every variable lives somewhere in memory, and every location in memory has a number — its address. A pointer is simply a variable that holds one of those addresses.

That is the whole idea. Pointers have a reputation for being hard, and the reputation comes from the notation, not the concept.

A pointer is a box that holds another box's address. *p follows the arrow.
c
#include <stdio.h>

int main(void)
{
    int age = 25;
    int *p = &age;     /* p holds the address of age */

    printf("age is        %d\n", age);
    printf("address of age %p\n", (void *) &age);
    printf("p holds       %p\n", (void *) p);
    printf("*p is         %d\n", *p);

    return 0;
}
Output
age is        25
address of age 0x7ffd4a2b3c4c
p holds       0x7ffd4a2b3c4c
*p is         25

Note

The actual address will differ every time you run it. That is normal — the operating system decides where your program sits in memory.

The two symbols

Reading pointer notation

  1. &age — "the address of age"

    The same & you have been writing in scanf all along. It asks: where does this variable live?

  2. int *p — "p points to an int"

    In a declaration, the star says what kind of thing p points at. p is not an int; p holds the address of an int.

  3. *p — "the value at that address"

    In an expression, the star does the opposite of &: it follows the address and fetches what is there. This is called dereferencing.

Warning

The star means two different things depending on where it is. In a declaration it creates a pointer. In an expression it follows one. Same symbol, opposite jobs — this is the single biggest source of confusion with pointers.

Now scanf makes sense

Back in lesson four you wrote scanf("%d", &age) and were told the & was needed so scanf could write into your variable. Now you know why: scanf takes a pointer. Without the & it would receive a copy of the value and write to whatever address that value happened to look like.

Given int n = 7; int *p = &n;, what is *p?

Create a free account to save your progress, or sign in.