Increment • Decrement • Array Navigation
Pointer arithmetic means performing math operations on pointers. You can move the pointer forward or backward in memory.
These operations are allowed:
Important: Pointer arithmetic moves by the size of the data type, not by bytes manually.
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;
}
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;
}
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;
}