C Pointer Arithmetic
Pointer arithmetic means doing math on pointers to move them around in memory. C is smart about this: when you add one to a pointer, it does not move one byte, it moves one whole element, based on the type the pointer refers to. This is what makes pointers such a natural fit for arrays.
Adding and subtracting
If p points to an int and one int takes four bytes on your system, then p + 1 skips ahead by four bytes to the next int. You never have to worry about the byte count yourself; the compiler scales the math by the size of the type.
Moving a pointer forward
#include <stdio.h>
int main() {
int data[3] = {100, 200, 300};
int *p = data;
printf("%d\n", *p); // 100
p++; // move to next int
printf("%d\n", *p); // 200
p++;
printf("%d\n", *p); // 300
return 0;
}The p++ step advances the pointer by one element each time. This is a common way to scan through data when you do not need an index counter.
The distance between two pointers
Subtracting one pointer from another that points into the same array tells you how many elements apart they are, not how many bytes. This is handy for measuring how far you have moved.
Counting elements between pointers
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *start = &arr[0];
int *end = &arr[4];
printf("Elements apart: %ld\n", end - start); // 4
return 0;
}- p + n moves the pointer forward by n elements.
- p - n moves it backward by n elements.
- p1 - p2 gives the element count between two pointers in the same array.
- Comparisons like p1 < p2 work when both point into the same array.