C Programming: Memory, Pointers and the Stack ยท Arrays and Strings

Arrays

A fixed-size block of values on the stack. Partly fill one, count its length with sizeof, and find the largest.

arrays.c

#include <stdio.h>

int main(void) {
    int marks[5] = {70, 82, 65};   /* the rest are set to 0 */
    int count = sizeof(marks) / sizeof(marks[0]);
    marks[3] = 90;
    int best = marks[0];
    for (int i = 1; i < count; i++) {
        if (marks[i] > best) {
            best = marks[i];
        }
    }
    printf("count=%d best=%d\n", count, best);
    return 0;
}

Step by step

  1. Five ints on the stack; the three given fill the start and the rest become 0.
  2. sizeof(marks) is 20 bytes, sizeof(marks[0]) is 4, so 5 elements.
  3. marks changes from [70, 82, 65, 0, 0] to [70, 82, 65, 90, 0].
  4. best is created on the stack with the value 70.
  5. i is created on the stack with the value 1.
  6. C checks marks[i] > best to decide which way the code goes.
  7. 82 > 70: new best.
  8. i changes from 1 to 2.
  9. C checks marks[i] > best to decide which way the code goes.
  10. i changes from 2 to 3.
  11. C checks marks[i] > best to decide which way the code goes.
  12. 90 beats 82.
  13. i changes from 3 to 4.
  14. C checks marks[i] > best to decide which way the code goes.
  15. i goes out of scope and disappears.
  16. It prints count=5 best=90.
  17. The method returns 0.
  18. count 5, best 90.