Coding

Pointers in C Explained With Examples

A pointer in C is a variable that holds the address of another object, declared with * and set with the address-of operator &. You read or write the object it points to with *, so int *p = &n; *p = 7; stores 7 in n.

The short version fits in one program. Compile it with any C compiler; the output shown is example output.

#include <stdio.h>

int main(void)
{
    int n = 1;
    int *p = &n;      /* p holds the address of n */

    *p = 7;           /* writes 7 into n through p */
    printf("%d\n", n);
    return 0;
}

Example output:

7

What is a pointer in C?

Every object in a C program lives somewhere in memory, and that location has an address. A pointer is an object whose value is such an address. The type of the pointer records what kind of object it refers to, so int * means "pointer to int". According to cppreference, a pointer may also refer to nothing, which is expressed by the special null pointer value.

Think of n as a house and p as a slip of paper with the house's street address. Copying the slip does not copy the house. Two pointers can hold the same address, and changing the object through one is visible through the other.

How do you declare a pointer?

The * belongs to the declarator, not to the type name. That matters when you declare several variables on one line:

int *a, b;     /* a is a pointer to int, b is a plain int */
int *c, *d;    /* both are pointers to int */

Writing one declaration per line avoids this trap. Pointers to pointers add another star (float **pp), and a pointer to a function looks like int (*fp)(int).

What do & and * do?

  • &n is the address-of operator. Applied to an object, it produces a pointer to that object.
  • *p is the indirection (dereference) operator. It gives you the object p points to, as something you can read or assign to.

The same * character appears in declarations and in expressions, but it means different things. In int *p it says "p is a pointer". In *p = 7 it says "follow p". For a pointer to a struct, p->field is shorthand for (*p).field.

Why pointers matter: changing a caller's variable

C passes arguments by value. A function gets a copy, so assigning to a parameter does not touch the caller's variable. Pass a pointer and the function can change the original:

#include <stdio.h>

void increment(int *counter)
{
    *counter += 1;
}

int main(void)
{
    int hits = 4;
    increment(&hits);
    printf("%d\n", hits);
    return 0;
}

Example output:

5

This is the main reason functions such as scanf take addresses: they need somewhere to put the result. If you come from a language that hides references, Python vs C: the differences covers how much more of this C leaves to you.

What is a null pointer?

A null pointer points to no object. You create one with the NULL macro or any integer constant expression with the value zero. Dereferencing a null pointer is undefined behavior, and two null pointers of the same type always compare equal. Functions that accept pointers usually need to check for null first. The standard library's free is the exception: it does nothing when given a null pointer.

int *p = NULL;
if (p != NULL) {
    *p = 1;      /* only runs when p points at something */
}

How does pointer arithmetic work?

Pointer arithmetic counts elements, not bytes. If P points at element index I of an array, then P + N points at element I + N of the same array. The compiler multiplies by the size of the element type, so with a 4-byte int, adding 1 moves the address by 4 bytes. That byte size is platform-specific; use sizeof instead of assuming it.

Subtracting two pointers into the same array gives the difference in elements, with the signed type ptrdiff_t from <stddef.h>:

#include <stddef.h>

int arr[5];
int *p = &arr[1];
int *q = &arr[4];
ptrdiff_t distance = q - p;   /* 3, because 4 - 1 */

The rules are strict. The behavior is defined only when both the original pointer and the result point at elements of the same array, or one past its end. Computing p - 1 when p points at the first element is undefined behavior, even if you never dereference the result. A pointer to a single object that is not part of an array is treated as a pointer to the first element of an array of size 1.

How are pointers and arrays related?

In most expressions, an array name converts to a pointer to its first element. That is why this works:

int a[3] = {10, 20, 30};
int *p = a;          /* same as &a[0] */

p[1];                /* 20 */
*(p + 2);            /* 30 */

Indexing p[i] is defined as *(p + i). Arrays and pointers are still different things: an array is the storage itself, and a pointer is a separate object holding an address. One visible difference is sizeof. For int a[3] it gives the size of three ints, while for a pointer it gives the size of the pointer. A function parameter written as int arr[] is really an int *, so the function cannot recover the array length. Pass the length as a separate argument.

How do you allocate memory with malloc?

malloc from <stdlib.h> returns a void * to a block of uninitialized storage, or a null pointer if the allocation fails. In C, a void * converts to any object pointer type without a cast. Release the block with free when you are done.

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

int main(void)
{
    int *squares = malloc(4 * sizeof *squares);
    if (squares == NULL) {
        return 1;                 /* allocation failed */
    }

    for (int i = 0; i < 4; ++i) {
        squares[i] = i * i;
    }
    for (int i = 0; i < 4; ++i) {
        printf("squares[%d] == %d\n", i, squares[i]);
    }

    free(squares);
    return 0;
}

Example output:

squares[0] == 0
squares[1] == 1
squares[2] == 4
squares[3] == 9

The idiom sizeof *squares sizes the block from the pointer's own type, so the line stays correct if you later change int to another type. Note that malloc(0) is implementation-defined: it may return null or a non-null pointer that you must not dereference but should still pass to free.

What are void pointers and function pointers?

A void * can hold the address of an object of any type. You cannot dereference it, because the compiler does not know what it points to. Generic interfaces such as malloc and qsort use it, and the caller is responsible for converting it back to the correct type.

A function pointer holds the address of a function. Calling fp(7) and (*fp)(7) are equivalent, and the & is optional when you take a function's address. Function pointers are how callbacks work in C, for instance the comparison function you pass to qsort.

Common pointer mistakes

  • Dereferencing a null or uninitialized pointer. Initialize pointers when you declare them, and check malloc results.
  • Using memory after free. After freeing, the pointer still holds the old address but the object is gone. Setting it to NULL makes a later mistake fail loudly instead of silently.
  • Going past the end of an array. Pointer arithmetic outside the array, other than one past the end, is undefined behavior.
  • Reading an object through the wrong type. Casting a pointer to an unrelated type and dereferencing it is almost always undefined behavior (the strict aliasing rules).
  • Returning the address of a local variable. The variable ceases to exist when the function returns, so the pointer dangles.
  • Forgetting to free. Memory from malloc that is never released is a leak.

Compilers and tools can catch many of these. Warnings such as GCC and Clang's -Wall -Wextra flag some, and runtime checkers such as AddressSanitizer (-fsanitize=address in both compilers) report invalid accesses while the program runs.

If your program crashes with a segmentation fault

A segmentation fault usually means the program touched memory it may not access, most often through a null, uninitialized or dangling pointer. Rebuild with -g and run under a debugger or AddressSanitizer to get the exact line. Because the language does not guarantee a crash for these errors, a program that seems to work is not proof that the pointers are correct.

Frequently asked questions

What is the difference between * and & in C?
The & operator gives the address of an object, so &n is a pointer to n. The unary * operator follows a pointer to the object it refers to, so *p reads or writes that object. In a declaration such as int *p, the * is part of the type and means 'pointer to int'.
What happens if I dereference a null pointer in C?
The behavior is undefined. On many systems the program crashes, for example with a segmentation fault, but the language does not guarantee a crash. Check a pointer for NULL before dereferencing it whenever it can legitimately be null, such as the result of malloc.
Why use a pointer instead of passing a value?
C passes arguments by value, so a function that receives a copy of an int cannot change the caller's variable. Passing a pointer to the variable lets the function modify the original. Pointers also let you work with arrays, dynamically allocated memory and functions without copying them.
What is a void pointer?
A void * can hold a pointer to an object of any type and converts to and from other object pointer types without a cast in C. You cannot dereference it or do arithmetic on it directly. Generic interfaces such as malloc and qsort use it, and the caller must convert it to the right type before use.

Sources