Lesson 20 / 36

Pointer Arithmetic

Moving a pointer means moving by whole elements, not bytes.

p + 1 skips a whole element

p + 1 doesn't add 1 byte — it adds sizeof(*p) bytes, moving to the next element of that type. This is what makes pointer + array indexing work seamlessly.

Walking an array via pointer

Adding to a pointer and dereferencing it is equivalent to array indexing.

int nums[3] = {5, 10, 15};
int *p = nums;         // points to nums[0]

printf("%d\n", *p);       // 5
printf("%d\n", *(p + 1)); // 10
printf("%d\n", *(p + 2)); // 15

Output:

5
10
15

Only within (or one past) the array

Pointer arithmetic is only well-defined within an array's bounds, or one element past the end (for comparison, never dereferenced). Going further is undefined behavior.