C Programming: Memory, Pointers and the Stack · Pointers

Pointer Arithmetic and Arrays

An array name acts as a pointer to its first element, and p++ moves to the next element, not the next byte.

pointer_arithmetic.c

#include <stdio.h>

int main(void) {
    int nums[4] = {10, 20, 30, 40};
    int *p = nums;            /* an array name becomes a pointer to its first element */
    int first = *p;
    p++;                      /* moves to the next int, not the next byte */
    int second = *p;
    int third = *(nums + 2);  /* same as nums[2] */
    int total = 0;
    for (int *q = nums; q < nums + 4; q++) {
        total += *q;
    }
    printf("%d %d %d %d\n", first, second, third, total);
    return 0;
}

Step by step

  1. nums is created on the stack with the value [10, 20, 30, 40].
  2. nums by itself becomes the address of nums[0], so p → nums[0].
  3. first is created on the stack with the value 10.
  4. p++ moves one int forward (4 bytes): now → nums[1].
  5. second is created on the stack with the value 20.
  6. *(nums + 2) is exactly nums[2]: 30.
  7. total is created on the stack with the value 0.
  8. q is created on the stack with the value → nums.
  9. q walks the array; *q reads each element.
  10. q changes from → nums to → nums[1].
  11. total changes from 10 to 30.
  12. q changes from → nums[1] to → nums[2].
  13. total changes from 30 to 60.
  14. q changes from → nums[2] to → nums[3].
  15. total changes from 60 to 100.
  16. q goes out of scope and disappears.
  17. It prints 10 20 30 100.
  18. The method returns 0.
  19. 10 20 30 100.