Pointer Arithmetic in C

Increment • Decrement • Array Navigation

1. What is Pointer Arithmetic?

Pointer arithmetic means performing math operations on pointers. You can move the pointer forward or backward in memory.

These operations are allowed:

  • p++ — move pointer to next element
  • p-- — move pointer to previous element
  • p = p + n — jump forward n elements
  • p = p - n — jump backward n elements

Important: Pointer arithmetic moves by the size of the data type, not by bytes manually.

2. Basic Pointer Increment

This example shows p++ moving to the next integer.

#include <stdio.h>

int main() {
    int a = 10;
    int b = 20;

    int *p = &a;

    printf("p points to a: %d\n", *p);

    p++; // moves to next integer (not +1 byte!)

    p = &b; // to avoid accessing random memory
    printf("Now p points to b: %d\n", *p);

    return 0;
}

3. Navigating Arrays Using Pointers

A pointer can walk through an array very easily.

#include <stdio.h>

int main() {

    int arr[] = {10, 20, 30, 40, 50};
    int *p = arr;  // same as &arr[0]

    printf("First: %d\n", *p);

    p++;  // move to arr[1]
    printf("Second: %d\n", *p);

    p += 2; // jump to arr[3]
    printf("Fourth: %d\n", *p);

    return 0;
}

4. Finding Distance Between Two Pointers

You can subtract two pointers inside the same array.

#include <stdio.h>

int main() {

    int arr[] = {5, 10, 15, 20, 25};
    int *p = &arr[1];
    int *q = &arr[4];

    int diff = q - p;  // gives number of elements apart

    printf("Distance: %d\n", diff);

    return 0;
}

5. Pointer Arithmetic Safety Rules

  • Only perform arithmetic inside the same array.
  • Never increment a NULL pointer.
  • Do not move pointer outside array bounds.
  • Pointer arithmetic depends on sizeof(type).

Try Code in Online Compiler