SyntaxStudy
Sign Up
C Pointer Basics: &, *, and Null
C Beginner 1 min read

Pointer Basics: &, *, and Null

A pointer is a variable that stores a memory address. Every variable in C has an address — the location in RAM where its value lives. The address-of operator `&` retrieves a variable's address. The dereference operator `*` reads or writes the value at a given address. Pointers are typed: an `int *` pointer knows that each step in pointer arithmetic should advance by the size of an `int`. The null pointer is a special pointer value that does not point to any valid object. In C11, `NULL` is defined in `` (and several other headers). Dereferencing a null pointer is undefined behaviour and almost always causes a program crash (segmentation fault on most systems). Always check that a pointer is non-NULL before dereferencing it, especially after dynamic memory allocation or after opening files. Pointer variables themselves occupy memory on the stack. On a 64-bit system, every pointer is 8 bytes regardless of what type it points to. You can have pointers to pointers (`int **`), which are used for output parameters of pointer type and for arrays of strings. The levels of indirection can be stacked arbitrarily, though more than two levels is uncommon and usually a sign of complex data structures.
Example
#include <stdio.h>
#include <stddef.h>   /* NULL */

int main(void)
{
    int  value = 42;
    int *ptr   = &value;   /* ptr holds the address of value */

    printf("value     = %d\n",  value);
    printf("&value    = %p\n",  (void *)&value);
    printf("ptr       = %p\n",  (void *)ptr);      /* same address */
    printf("*ptr      = %d\n",  *ptr);             /* 42           */

    /* Modifying through a pointer */
    *ptr = 100;
    printf("value after *ptr=100: %d\n", value);   /* 100          */

    /* Pointer to pointer */
    int **pptr = &ptr;
    printf("**pptr    = %d\n", **pptr);            /* 100          */

    /* Null pointer check */
    int *p = NULL;
    if (p == NULL) {
        printf("p is NULL — safe, not dereferencing\n");
    }

    /* sizeof a pointer (platform-dependent) */
    printf("sizeof(int *) = %zu bytes\n", sizeof(int *));

    /* Pointer comparison */
    int arr[5] = {1, 2, 3, 4, 5};
    int *start = arr;
    int *end   = arr + 5;
    printf("Elements via comparison: ");
    for (int *q = start; q < end; q++)
        printf("%d ", *q);
    printf("\n");

    return 0;
}