Pointers & Memory · beginner · ~10 min
Move within an array and explain the one-past-the-end boundary.
Pointer arithmetic moves in elements of the pointed-to type. Use a small array to see where each increment goes. The goal is to recognize the valid range before writing a loop, not to memorize numeric addresses.
For int a[3], a + 1 points to the second int, regardless of how many bytes an int occupies. a[i] and *(a + i) access the same element for a valid index.
You may form a + 3, the one-past pointer, and compare it to pointers within this array. You may not dereference it or form a + 4. Subtraction is defined for pointers into the same array (including one-past), when the difference is representable in ptrdiff_t. It yields an element count, not a byte count. Do not subtract pointers to unrelated objects.
Pointer arithmetic moves in elements of the pointed-to type. Use a small array to see where each increment goes. The goal is to recognize the valid range before writing a loop, not to memorize numeric addresses.
#include <stdio.h>
#include <stddef.h>
int main(void) {
int a[] = {10, 20, 30};
int *end = a + 3;
printf("%d %td\n", *(a + 1), end - a);
return 0;
}
Expected output on a successful allocation, where applicable:
20 3
a + 1 identifies the second element. end marks the boundary after the third element. Subtracting the start from this boundary gives three elements; the boundary itself is never read.
*(a + 1) with *(a + 3) is invalid; do not run the invalid access.Pointer offsets count elements. A one-past pointer is a boundary, not an element. Keep arithmetic and subtraction within one array and use ptrdiff_t for differences.