Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

C
C
0/12 completed
Beginner
Hello CVariables and typesOperators and control flowFunctions
Intermediate
Arrays and stringsPointersStructs, enums and unions
Advanced
Dynamic memoryFile I/OThe preprocessor and multi-file programs
Pro
Build tools and MakeDebugging, sanitizers and safe C
Tracks / C / Intermediate

Pointers

A pointer is a variable that holds a memory address: the location of some other value. Pointers are what make C powerful (and what make it hard). Once they click, you'll also understand how references work in Python, Java and JavaScript, because those languages use pointers internally, they just hide them.

Addresses and &

Every variable lives at some address in memory. The & operator gives you that address:

c
#include <stdio.h>

int main(void) {
    int age = 31;
    double price = 9.99;
    printf("age   = %d, stored at %p, size %zu bytes\n", age, (void *)&age, sizeof age);
    printf("price = %.2f, stored at %p, size %zu bytes\n", price, (void *)&price, sizeof price);
    return 0;
}
Output
age   = 31, stored at 0xffffc267ca3c, size 4 bytes
price = 9.99, stored at 0xffffc267ca30, size 8 bytes

%p prints an address in hexadecimal. The exact numbers change on every run (the system randomises memory layout for security), so don't worry about them. What matters is what you can do with an address.

Declaring and using pointers

c
#include <stdio.h>

int main(void) {
    int score = 10;
    int *p = &score;          // p is a "pointer to int", holding the address of score

    printf("score = %d\n", score);
    printf("*p    = %d\n", *p);      // * follows the pointer: "the int at that address"

    *p = 25;                  // change score THROUGH the pointer
    printf("score is now %d\n", score);

    printf("p == &score? %s\n", p == &score ? "yes" : "no");
    printf("a pointer itself uses %zu bytes\n", sizeof p);
    return 0;
}
Output
score = 10
*p    = 10
score is now 25
p == &score? yes
a pointer itself uses 8 bytes
Code Meaning
int *p; Declare p as a pointer to an int
p = &x; Store the address of x in p ("p points to x")
*p Dereference: the value p points to. Read it or assign to it
p->field The field of a struct that p points to (next lesson)

The * means two different things: in a declaration (int *p) it says "this is a pointer"; in an expression (*p = 25) it says "go to the address". On a 64-bit system every pointer is 8 bytes, whatever it points to.

Why pointers? Changing a caller's variables

You saw in Functions that C copies arguments. Passing a pointer lets the function reach back into the caller's memory:

c
#include <stdio.h>

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

void stats(const int *values, int n, int *sum, double *avg) {
    *sum = 0;
    for (int i = 0; i < n; i++) *sum += values[i];
    *avg = n ? (double)*sum / n : 0;
}

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

    int data[] = {4, 8, 15, 16, 23, 42};
    int total;
    double mean;
    stats(data, 6, &total, &mean);
    printf("sum %d, average %.2f\n", total, mean);
    return 0;
}
Output
x = 2, y = 1
sum 108, average 18.00

That's the reason scanf("%d", &n) needs the &: it must write into your variable.

NULL: a pointer to nothing

A pointer that doesn't point anywhere should be NULL (or nullptr in C23). Functions return it to say "not found" or "failed", and you must check before dereferencing:

c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "find the needle here";
    const char *hit = strstr(text, "needle");
    const char *miss = strstr(text, "pin");

    if (hit != NULL) printf("found at position %td: \"%s\"\n", hit - text, hit);
    if (miss == NULL) printf("\"pin\" not found\n");
    return 0;
}
Output
found at position 9: "needle here"
"pin" not found

Dereferencing NULL crashes the program with a segmentation fault: the operating system stops it for touching memory it doesn't own.

main.c
#include <stdio.h>

int main(void) {
    int *p = NULL;
    printf("about to dereference NULL…\n");
    printf("%d\n", *p);
    return 0;
}
bash
./main
Output
about to dereference NULL…
bash: line 1:   121 Segmentation fault      ./main
exit code: 139

Exit code 139 is 128 + 11, where 11 is SIGSEGV, the segmentation-fault signal. Every C programmer meets this message; the Debugging lesson shows how to find the exact line in seconds.

Pointers and arrays

An array's name, used in an expression, turns into a pointer to its first element. And adding to a pointer moves it by whole elements, not bytes:

c
#include <stdio.h>

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

    printf("*p       = %d\n", *p);
    printf("*(p + 2) = %d\n", *(p + 2));      // same as nums[2]
    printf("p[3]     = %d\n", p[3]);          // [] works on pointers too
    printf("(char *)(p + 1) - (char *)p = %td bytes\n", (char *)(p + 1) - (char *)p);

    for (int *q = nums; q < nums + 4; q++) printf("%d ", *q);
    printf("\n");
    return 0;
}
Output
*p       = 10
*(p + 2) = 30
p[3]     = 40
(char *)(p + 1) - (char *)p = 4 bytes
10 20 30 40

a[i] is defined as *(a + i). That's why arrays and pointers can be used almost interchangeably, and why a function parameter written int a[] is really int *a.

Walking a string with a pointer

c
#include <stdio.h>

size_t my_strlen(const char *s) {
    const char *start = s;
    while (*s != '\0') s++;
    return (size_t)(s - start);    // pointer subtraction = number of elements between
}

int main(void) {
    printf("%zu\n", my_strlen("pointers"));
    printf("%zu\n", my_strlen(""));
    return 0;
}
Output
8
0

const and pointers

const can protect the value being pointed to, the pointer itself, or both:

c
#include <stdio.h>

int main(void) {
    int a = 1, b = 2;

    const int *p1 = &a;   // can't change *p1, can move p1
    p1 = &b;

    int *const p2 = &a;   // can change *p2, can't move p2
    *p2 = 10;

    printf("a = %d, *p1 = %d\n", a, *p1);
    return 0;
}
Output
a = 10, *p1 = 2

Read declarations from right to left: const int *p is "p is a pointer to an int that is const". Mark pointer parameters const whenever the function only reads through them, like strlen(const char *s). It documents the function and the compiler enforces it.

Pointers to pointers

A pointer can point to another pointer. You'll see this with arrays of strings (like main's argv) and when a function needs to change a pointer:

args.c
#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("argc = %d\n", argc);
    for (int i = 0; i < argc; i++) {
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    }
    char **p = argv;          // argv is a char ** in disguise
    printf("first letter of the first argument: %c\n", argc > 1 ? p[1][0] : '-');
    return 0;
}
bash
gcc -std=c23 -Wall -Wextra -o args args.c
./args deploy --env 'staging eu'
Output
argc = 4
argv[0] = "./args"
argv[1] = "deploy"
argv[2] = "--env"
argv[3] = "staging eu"
first letter of the first argument: d

main(int argc, char *argv[]) receives the command-line arguments: argc counts them, argv is an array of strings, and argv[0] is the program's name.

Function pointers

Functions have addresses too. A function pointer lets you pass behaviour as an argument, like a callback. The standard library's qsort uses one to know how to compare elements:

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int by_number(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

int by_text(const void *a, const void *b) {
    return strcmp(*(const char *const *)a, *(const char *const *)b);
}

int main(void) {
    int nums[] = {42, 7, 19, 3, 25};
    qsort(nums, 5, sizeof nums[0], by_number);
    for (int i = 0; i < 5; i++) printf("%d ", nums[i]);
    printf("\n");

    const char *names[] = {"Ravi", "Asha", "Zoe", "Lee"};
    qsort(names, 4, sizeof names[0], by_text);
    for (int i = 0; i < 4; i++) printf("%s ", names[i]);
    printf("\n");

    double (*op)(double) = NULL;   // a pointer to a function taking and returning double
    (void)op;
    return 0;
}
Output
3 7 19 25 42
Asha Lee Ravi Zoe

void * is a generic pointer: it can hold the address of anything, but you must convert it back to the real type before using it. That's how qsort sorts arrays of any type.

The rules that keep you safe

  1. Initialise every pointer, to a real address or NULL.
  2. Check for NULL before dereferencing anything a function returned.
  3. Never return the address of a local variable: it stops existing when the function returns.
  4. Stay inside the array. Pointer arithmetic past the end is undefined behaviour.
  5. After free(p) (next lessons), set p = NULL.

Rule 3 in action, caught by the compiler:

c
#include <stdio.h>

int *broken(void) {
    int local = 42;
    return &local;
}

int main(void) {
    int *p = broken();
    printf("%p\n", (void *)p);
    return 0;
}
Output
main.c: In function ‘broken’:
main.c:5:12: warning: function returns address of local variable [-Wreturn-local-addr]
    5 |     return &local;
      |            ^~~~~~
(nil)

GCC even replaced the address with (nil) (NULL) because using it would be meaningless.

Practice

  1. Write void to_upper(char *s) that changes a string in place, walking it with a pointer.
  2. Write int *find(int *a, size_t n, int value) that returns a pointer to the first match or NULL.
  3. Sort an array of doubles in descending order with qsort.
  4. Print every command-line argument backwards (last argument first, each one reversed).
✎ Check your understanding

1.int x = 5; int *p = &x; What is *p?

2.Why does scanf("%d", &n) need the &?

3.If int *p points to nums[0], what does p + 1 point to?

4.What happens when you dereference a NULL pointer?

← Arrays and strings