Core Concepts

Pointers

Master C pointers — the most powerful and distinctive feature of the C language.

What is a Pointer?

A pointer is a variable that stores a memory address. Instead of holding a value directly, it holds the location of a value.

Pointer Operators

  • & — address-of operator: get the address of a variable
  • * — dereference operator: get the value at an address

Pointer Arithmetic

You can add/subtract integers from pointers. This moves the pointer by multiples of the pointed-to type's size. This is the basis of array access.

Null Pointer

Always initialize pointers. Use NULL for a pointer that doesn't point to anything valid.

Example

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

int main() {
    int x = 42;
    int *ptr;      /* pointer to int */

    ptr = &x;      /* ptr holds the address of x */

    printf("Value of x: %d\n", x);
    printf("Address of x: %p\n", (void*)&x);
    printf("Value of ptr: %p\n", (void*)ptr);
    printf("Value at ptr: %d\n", *ptr);  /* dereference */

    /* Modify through pointer */
    *ptr = 100;
    printf("x is now: %d\n", x);  /* 100 */

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

    /* Pointer arithmetic and arrays */
    int arr[5] = {10, 20, 30, 40, 50};
    int *p = arr;  /* array name is a pointer to first element */

    for (int i = 0; i < 5; i++) {
        printf("%d ", *(p + i));  /* same as arr[i] */
    }

    /* Null pointer */
    int *nullPtr = NULL;
    if (nullPtr == NULL) {
        printf("\nPointer is null\n");
    }

    /* Dynamic memory allocation */
    int *dynArr = malloc(5 * sizeof(int));
    if (dynArr != NULL) {
        for (int i = 0; i < 5; i++) dynArr[i] = i * 10;
        for (int i = 0; i < 5; i++) printf("%d ", dynArr[i]);
        free(dynArr);  /* ALWAYS free allocated memory */
    }

    return 0;
}
Try it yourself — C