CodeMIRAI
0 XP

Pointers

2 min read 3 runnable examples Quiz included

Every variable lives somewhere in memory, at an address. A pointer is a variable that stores an address.

& gives an address, * follows it

C
#include <stdio.h>

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

    printf("age        = %d\n", age);
    printf("*p         = %d\n", *p);    // the value p points to
    *p = 30;                            // change age through the pointer
    printf("age now    = %d\n", age);
    return 0;
}
int x = 42; · int *p = &x;0x100042x0x1004…0x20000x1000p&x is x's address: 0x1000p holds that address*p follows it, reading 42*p = 7; changes x through the pointer
A pointer is a variable whose value is an address. & takes an address; * follows one.
  • &age means "the address of age".
  • int *p declares p as a pointer to an int.
  • *p means "the value at the address in p" (called dereferencing).

Changing a variable from a function

In the functions lesson, a function couldn't change the caller's variable because C passes copies. Pass the variable's address instead, and the function can reach the original:

C
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 1, y = 2;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

This is exactly why scanf("%d", &n) needs &n: scanf needs to know where to write the number.

Pointers and arrays

An array's name acts as a pointer to its first element, and adding to a pointer moves it along the array:

C
#include <stdio.h>

int main() {
    int nums[4] = {10, 20, 30, 40};
    int *p = nums;          // same as &nums[0]

    printf("%d\n", *p);         // 10
    printf("%d\n", *(p + 1));   // 20
    printf("%d\n", p[2]);       // 30: indexing works on pointers too
    for (int i = 0; i < 4; i++) {
        printf("%d ", *(p + i));
    }
    printf("\n");
    return 0;
}

*(p + i) and p[i] mean the same thing; array indexing is pointer arithmetic underneath.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.