← C roadmap

Topic 6 of 15 · Intermediate

Pointers

Addresses, dereferencing, pointer arithmetic and arrays.

Concept

A pointer stores a memory address. &x gives x's address; *p reads or writes the value at that address.

Pointer arithmetic moves by element size: p + 1 points to the next int, 4 bytes later. An array name decays to a pointer to its first element, so a[i] == *(a + i).

Always initialise pointers (to NULL if nothing else). Dereferencing NULL or a dangling pointer crashes or corrupts memory.

Code (C17)

#include <stdio.h>

int main(void) {
    int x = 10;
    int *p = &x;
    *p = 20;
    printf("x = %d, address = %p\n", x, (void *)p);

    int a[] = {5, 10, 15};
    int *q = a;
    printf("%d %d\n", *(q + 1), q[2]);    // 10 15

    int **pp = &p;                         // pointer to pointer
    printf("%d\n", **pp);                  // 20
    return 0;
}

Remember

  • a[i] is *(a + i).
  • Initialise pointers; check for NULL.
  • void* is a generic pointer.

Interview questions

What is a dangling pointer?

A pointer to memory that has been freed or has gone out of scope. Set pointers to NULL after free.

const int *p vs int *const p?

const int *p: can't change the value through p. int *const p: can't change where p points.

Practise C with the AI mentor

Lesson test

Take an 8-question test on “Pointers” — concepts, output prediction, bug spotting and interview questions.

Can't find a C topic you need for exams or placements? Request it and we'll add it.