Pointers & Memory · beginner · ~10 min
Increment, compare, and subtract pointers correctly.
When you add 1 to a pointer of type T *, the pointer does not move forward by one byte. It moves forward by sizeof(T) bytes — the size of one element.
This is what makes p++ walk through an array of any type correctly. Each step lands exactly on the next element, whatever its size.
Example: if int is 4 bytes, then for an int *p, writing p + 1 moves the address forward by 4 bytes, not 1.
Two pointers that point into the same array can be:
< and ==.p - q gives the number of elements between them (not the number of bytes).Comparing or subtracting pointers that point into different arrays is undefined behaviour. Undefined behaviour means the C standard places no requirements on what happens — the result is not reliable, so never do it.
int a[5] = {10,20,30,40,50};
int *p = a;
int *end = a + 5;
while (p < end) { printf("%d ", *p); p++; }
p + 1 advances by one byte. It actually advances by sizeof(*p) — the size of one element.1 to a T * moves it forward by sizeof(T) bytes, so p++ steps to the next element.<, ==) and subtracted; p - q counts elements between them.