Pointer Arithmetic & Arrays
Pointer arithmetic is scaled by the pointed-to type. If p points to an int and int is four bytes, p + 1 advances by four bytes.
In plain English
Pointer arithmetic is walking down a street in steps the size of one house.
Scaling and array equivalence
Adding 1 to a pointer moves it by one element, not one byte. The compiler multiplies the integer offset by the size of the pointed-to type. An array name decays to a pointer to its first element in most expressions, so a[i] is equivalent to *(a + i). The pointer must stay within the array or one past its end.
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d\n", *p); /* 10 */
printf("%d\n", *(p + 2)); /* 30 */
printf("%d\n", p[3]); /* 40 */Unary ++ and -- on pointers
The ++ and -- operators move a pointer forward or backward by one element. They are useful for walking an array, but they mutate the pointer itself. Keep a separate pointer if you still need the original base address. Postfix and prefix forms differ in when the old value is used, just like with integers.
int a[3] = {5, 10, 15};
int *p = a;
printf("%d\n", *p++); /* prints 5, then p moves to a[1] */
printf("%d\n", *p); /* 10 */
printf("%d\n", *++p); /* p moves to a[2], prints 15 */Watch it happen
Step through the memory changes one instruction at a time.
step-by-step
Step 1 of 6
Create the array
int a[4] = {10, 20, 30, 40}; stores four ints contiguously. Each int is 4 bytes here.
Key takeaways
- Pointer arithmetic moves in units of the pointed-to type.
- a[i] is equivalent to *(a + i).
- An array name decays to a pointer to its first element.
- ++ and -- mutate the pointer itself.
Common pitfalls
- Assuming p + 1 adds one byte.
- Going outside the bounds of an array.
- Losing the base pointer after incrementing it.
Key focus
- Trace pointer values and dereferenced values step by step.
- Know why a[i] equals *(a + i).
Quick check
1. If int *p points to an int at address 1000 and int is 4 bytes, what is p + 1?
2. Which expression is equivalent to a[2]?