First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Pointers

Pointers in C: what they are, how to declare, initialize, dereference, do pointer arithmetic, use NULL/void/const, pointer-to-pointer and function pointers, plus safe practices and exam-ready examples.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Pointers are how C works with memory locations directly: they store addresses of variables, arrays, functions, and dynamically allocated memory. Engineers use pointers to pass large data to functions efficiently, build data structures (linked lists, trees), interface with hardware, and write fast, memory‑efficient code.

Key ideas

  • Definition: An address is a number that identifies a byte in memory. In C, addresses are obtained using the address‑of operator & applied to an lvalue (like a variable).
  • Definition: Dereferencing (or indirection) is accessing the object a pointer points to, using the * operator. If p is a pointer to int, then *p is the int stored at that address.
  • Definition: A null pointer is a special pointer value that is guaranteed to compare unequal to any valid object or function address. In C, the macro NULL provides a null pointer constant.
  • Definition: A wild pointer (or uninitialized pointer) is a pointer with an indeterminate value. Dereferencing it leads to undefined behavior.
  • Definition: A dangling pointer is a pointer that used to point to a valid object but does not anymore because the object’s lifetime ended (e.g., a local variable after its function returns). Using it is undefined behavior.
  • Definition: A void pointer (void *) is a pointer type that can hold the address of any object type. It cannot be directly dereferenced without casting to a pointer to a complete type.
  • Definition: A pointer to pointer is a pointer whose value is the address of another pointer (e.g., int **pp holds the address of an int *).
  • Definition: A function pointer is a pointer that holds the address of a function, allowing indirect calls to functions.
  • Definition: Pointer arithmetic means adding or subtracting an integer to/from a pointer, or subtracting two pointers to the same array, in units of the pointed‑to type size. It is only defined within the bounds of a single array object and one element past the last.
  • Definition: Pointer comparison: Relational comparisons (<, >, <=, >=) are defined only for pointers that point into the same array object (or one past the end). Equality/inequality (==, !=) are defined for any two pointers to compatible types (including comparisons with a null pointer).
  • Definition: const with pointers has two independent meanings:
    • const int *p: pointer to constant int (you cannot modify the int via p).
    • int *const p: constant pointer to int (the pointer value cannot change; the int can).
    • const int *const p: constant pointer to constant int.
  • Definition: Type compatibility in pointers: A pointer type must match the type of object it points to for correct dereferencing. Implicit conversions between object pointer types are not generally allowed (except to/from void *). Function pointers are not compatible with object pointers.
  • Exact statement (address-of/dereference inverse law under valid conditions): If T x; is an object with storage, then &x yields its address of type T *, and if p = &x, then *p designates x. Assumption: x has a valid lifetime, and p is not null and properly aligned.
  • Exact statement (null pointer rule): Comparing any pointer p to NULL yields true if and only if p is a null pointer. Dereferencing a null pointer is undefined behavior.
  • Exact statement (pointer arithmetic rule): If p is a pointer to the first element of an array object A with n elements, then for any integer k in [0, n], p + k points to the k‑th element (or one‑past‑last when k == n). Accessing or dereferencing outside [0, n-1] is undefined behavior. Subtracting two pointers p + i and p + j (into the same array) yields i - j of type ptrdiff_t.
  • Exact statement (array‑to‑pointer decay, brief): Except when it is the operand of sizeof, _Alignof, or unary &, or is a string literal used to initialize an array, an expression of array type is converted to a pointer to its first element. Note: Full coverage with arrays/strings is in “Pointers with arrays and strings”.
  • Memory model notes:
    • Every object has a lifetime and alignment requirement. A pointer must be appropriately aligned for its type to be safely dereferenced.
    • The size of pointers can vary by platform and can differ between object and function pointers.
  • Safety practices:
    • Initialize pointers when you declare them (to NULL or to a known address like &var).
    • Check pointers against NULL before dereferencing when a function may return NULL.
    • Limit pointer arithmetic to within the same array.
    • Match format specifiers correctly (use %p for pointers after casting to (void *)).

Diagram to draw and label (for an exam answer):

  • Draw a box labeled “x (int)” with value 10 written inside. Below or beside it, write an address label like “address: 1000” (do not claim an actual number in code; this is a conceptual diagram).
  • Draw another box labeled “p (int *)” with value “1000”.
  • Draw an arrow from box p to box x to show that p holds the address of x. Label the arrow “p points to x; *p is 10”.

Formulas

  • p = &x; — assign address of variable x to pointer p (types must match: T and type of x).
  • *p — dereference p to access the object it points to.
  • p == NULL — test for null pointer.
  • void *vp = p; — any object pointer can convert to/from void* implicitly.
  • const T *p; — pointer to constant T (cannot modify *p).
  • T *const p = &x; — constant pointer to T (p cannot change, *p can).
  • p + k, p - k — pointer arithmetic in units of sizeof(*p); only within same array.
  • p2 - p1 — difference of two pointers into the same array; result type ptrdiff_t.
  • int **pp = &p; — pp is pointer to pointer to int.
  • int (*fptr)(int, int) = &func; — function pointer to a function taking two ints and returning int; call via fptr(a, b) or (*fptr)(a, b).
  • scanf("%d", &x); — pass address to input functions to allow them to modify x.
  • printf("%p\n", (void *)p); — print an address (implementation‑defined format, do not assume numeric base).

Worked examples

Example 1: Basic pointer declaration, initialization, and dereference to modify a variable

Program:

#include <stdio.h>

int main(void) {
    int x;               // ordinary integer variable
    int *p = NULL;       // pointer to int, initialized to NULL

    printf("Enter an integer: ");
    if (scanf("%d", &x) != 1) {
        printf("Invalid input\n");
        return 1;
    }

    p = &x;              // p now holds the address of x
    *p = *p + 10;        // add 10 to x via the pointer

    printf("After adding 10 via pointer, x = %d\n", x);
    printf("Value through pointer *p = %d\n", *p);

    return 0;
}

Sample input:

42

Exact output:

Enter an integer: After adding 10 via pointer, x = 52
Value through pointer *p = 52

Example 2: Swapping two integers using pointers (pass‑by‑reference style)

Program:

#include <stdio.h>

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

int main(void) {
    int a, b;

    printf("Enter two integers: ");
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Invalid input\n");
        return 1;
    }

    printf("Before swap: a = %d, b = %d\n", a, b);
    swap(&a, &b);  // pass addresses so swap can modify originals
    printf("After swap:  a = %d, b = %d\n", a, b);

    return 0;
}

Sample input:

5 9

Exact output:

Enter two integers: Before swap: a = 5, b = 9
After swap:  a = 9, b = 5

Example 3: Pointer arithmetic within an array (sum and pointer difference)

Program:

#include <stdio.h>
#include <stddef.h> // for ptrdiff_t

int main(void) {
    int n = 5;
    int arr[5];

    printf("Enter 5 integers: ");
    if (scanf("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]) != 5) {
        printf("Invalid input\n");
        return 1;
    }

    int *p = arr;        // points to first element (arr decays to &arr[0])
    long long sum = 0;

    while (p < arr + n) { // one-past-the-end is arr + n
        sum += *p;        // add current element
        p++;              // move to next element
    }

    ptrdiff_t diff = &arr[4] - &arr[1]; // valid: both within same array

    printf("Sum = %lld\n", sum);
    printf("Pointer difference (&arr[4] - &arr[1]) = %td\n", diff);

    return 0;
}

Sample input:

10 20 30 40 50

Exact output:

Enter 5 integers: Sum = 150
Pointer difference (&arr[4] - &arr[1]) = 3

Notes on the examples:

  • We avoided printing raw addresses because the exact address format and value are implementation‑defined; %p prints an address but its representation varies by system.
  • Pointer arithmetic was done only within a single array (arr). The difference 3 is well‑defined and is in units of elements, not bytes.

Common mistakes

  • Forgetting & in scanf (e.g., writing scanf("%d", x); instead of scanf("%d", &x);). scanf needs the address to store input.
  • Dereferencing NULL or an invalid pointer value, causing undefined behavior/crashes.
  • Assuming pointer size equals sizeof(int) or is always 4 bytes. Pointer size depends on the platform and pointer kind.
  • Mixing pointer types, e.g., assigning int * to char * and dereferencing without a proper cast and understanding of aliasing and alignment.
  • Performing pointer arithmetic across different arrays or beyond one‑past‑the‑end.
  • Using %d or %u to print a pointer instead of %p with a cast to (void *).
  • Confusing const int *p with int *const p. The former protects the pointed value; the latter fixes the pointer itself.
  • Creating a dangling pointer by returning the address of a local variable from a function, then using it.
  • Incrementing a void * pointer (not allowed in standard C; void has no size). Convert to a pointer to a complete type first, such as char *.
  • Taking the address of a temporary or of an expression that is not an lvalue (e.g., &(a + b)), which is invalid.

For your exam

  • Short notes: const with pointers; pointer comparison rules; array‑to‑pointer decay (brief); safety practices. Include a neat labeled memory diagram where relevant.
  • Programs: swap two numbers using pointers; sum array elements using pointer arithmetic; demonstrate pointer to pointer to change a variable; simple function pointer usage to call one of two functions based on input. Ensure your code compiles, runs, and produces the shown output for given inputs.
  • Tracing: Given a snippet with pointers and increments, state final values of variables and the pointer’s target. Show step‑by‑step changes.
  • Reasoning: Explain why p = &x; *p = 5; modifies x. State assumptions (x has valid lifetime; p is properly aligned; p not null).
  • Rules: When is pointer subtraction valid? State that both pointers must point into the same array (or one past), and the result is in elements of type ptrdiff_t.
  • Format specifiers: What specifier prints a pointer? Answer: %p with (void *) cast.
  • Do not claim a specific pointer size or address value; if asked, state “implementation‑defined; depends on platform/ABI; object and function pointer sizes may differ.”

Tips to earn full marks:

  • Define each term in one crisp sentence and then illustrate with a 2–3 line code example or a clear diagram description.
  • State the assumptions under which each rule holds (same array, valid lifetime, proper alignment, non‑null).
  • For programs, include correct headers, input validation, and exact sample I/O. Avoid implementation‑defined outputs like raw addresses.

Quick check

  1. Write a single declaration for: p is a pointer to a constant float.
  2. What does & do and what does * do in pointer context?
  3. Declare a pointer to a function that takes two float arguments and returns an int.

Answers: 1) const float *p; 2) & gives the address of an object (address‑of); * on a pointer accesses the object it points to (dereference). 3) int (*fp)(float, float);

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?