Pointer Arithmetic
beginner15 min readLesson 43 of 148
p + 1 doesn't move one byte โ it moves one ELEMENT, guided by the pointer's type.
+1 means "one element further"
int a[5] = {5, 10, 15, 20, 25};
int *p = a; // &a[0]
printf("%d\n", *p); // 5
printf("%d\n", *(p + 1)); // 10 โ one INT further (4 bytes), not one byte
printf("%d\n", *(p + 2)); // 15
The compiler scales arithmetic by sizeof(type): for int*, +1 is +4 bytes;
for double*, +1 is +8. That is why pointer types matter.
Indexing IS pointer arithmetic
a[i] is defined as *(a + i)
a[3], 3[a], *(a+3) โ all the same address. The bracket notation exists
for readability, not because it is a different mechanism.
Walking with a pointer
int *p = a;
int *end = a + 5; // one PAST the last element โ legal to hold
while (p < end) {
printf("%d ", *p);
p++; // advance one element
}
You may compute and compare pointers one past the end; dereferencing there is undefined behavior.
Subtraction gives distance
int *p = &a[2];
printf("%ld\\n", (long)(p - a)); // 2 โ element count, not bytes
What is NOT legal
- arithmetic between unrelated arrays:
p1 - p2where they point into different arrays โ undefined - dereferencing one-past-the-end, or any address outside the array
- scaling with pointers to incomplete objects