C - Pointer arithmetic
Pointer Arithmetic in C
Pointers can be incremented, decremented, and offset with +/-. Movement is in units of the pointee type (e.g., p+1 for int* advances by sizeof(int) bytes).
Learning Objectives
- Use p++,p--, andp + ksafely within array bounds.
- Understand how element size affects pointer movement.
Prerequisites
Example
#include <stdio.h>
int main(void) {
    int arr[3] = {10, 20, 30};
    int *p = arr; // &arr[0]
    printf("%d\n", *p); // 10
    p++;
    printf("%d\n", *p); // 20
}
More Examples
Iterate with offsets
#include <stdio.h>
int main(void) {
  int arr[] = {5, 15, 25, 35, 45};
  int *ptr = arr;
  int n = (int)(sizeof arr / sizeof arr[0]);
  for (int i = 0; i < n; i++) {
    printf("%d ", *(ptr + i));
  }
}
Reverse traversal
#include <stdio.h>
int main(void) {
  int arr[] = {2, 4, 6, 8, 10};
  int *ptr = arr + 4; // last element
  for (int i = 4; i >= 0; i--) {
    printf("%d ", *(ptr - i));
  }
}
Other types
#include <stdio.h>
int main(void) {
  double arr[] = {1.1, 2.2, 3.3};
  double *ptr = arr;
  ptr += 2;
  printf("%.1f\n", *ptr); // 3.3
}
Common Pitfalls
- Pointer arithmetic outside the bounds of the same array has undefined behavior.
- Don’t mix pointer arithmetic with freed memory.
Checks for Understanding
- What does p + 1do for achar*vs anint*?
Show answers
- Advances by 1 byte for char*and bysizeof(int)bytes forint*.