Pointers

A variable that holds an address

A pointer is a variable whose value is an address. It "points at" another variable.

#include <stdio.h>

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

    printf("age = %d\n", age);
    printf("*p  = %d\n", *p);
    return 0;
}

Output

age = 25
*p  = 25
  • int *p creates a pointer to an int. The * means "pointer".
  • = &age stores the address of age in it.
  • *p means "go to the address in p and look at the value there". This is called dereferencing.

Think of it like this: A pointer is like a piece of paper with a house address written on it. The paper is not the house – but if you follow the address (*p), you reach the house and can see what's inside.

Changing a value through a pointer

*p can also be used on the left of =. That changes the variable it points to:

#include <stdio.h>

int main() {
    int score = 10;
    int *p = &score;
    *p = 99;
    printf("score is now %d\n", score);
    *p += 1;
    printf("score is now %d\n", score);
    return 0;
}

Output

score is now 99
score is now 100

We never wrote score = ..., yet score changed – because p points at it.

The two meanings of *

WhereMeaning
In a declaration: int *p;"p is a pointer to an int"
In an expression: *p = 5;"the value at the address in p"

NULL: pointing at nothing

A pointer that doesn't point anywhere yet should be set to NULL. Always check before using it:

#include <stdio.h>

int main() {
    int *p = NULL;
    if (p == NULL) {
        printf("p doesn't point anywhere yet\n");
    }
    return 0;
}

Output

p doesn't point anywhere yet

Common mistake: Using *p when p is NULL or was never given an address. The program crashes (or worse, silently changes random memory).

HOME LABS COMMUNITY DASHBOARD