Arrays in memory

An array is several values of the same type, stored contiguously: one right after another, no gaps.

int scores[4] = {70, 85, 90, 64};

With 4-byte ints, that is one 16-byte block. If scores[0] starts at some address A, then scores[1] is at A + 4, scores[2] at A + 8, and so on. That is why indexing starts at 0: the index is "how many elements past the start". Getting element i is just one multiply and one add, which is why arrays are fast.

index:    [0]   [1]   [2]   [3]
value:     70    85    90    64
offset:    +0    +4    +8   +12   (bytes)

The size of an array is fixed when you declare it. sizeof on the array gives the total bytes, so this classic trick counts its elements:

int count = sizeof(scores) / sizeof(scores[0]);   // 16 / 4 = 4

That only works where the array was declared. Pass it to a function and it turns into a pointer (more on that in a later lesson), and sizeof would measure the pointer instead.

Now the scary part. C does not check array bounds. scores[4] or scores[-1] compile fine and are undefined behaviour: you might read a neighbouring variable, get garbage, corrupt something, or crash. Many real security bugs, buffer overflows, are exactly this. Keeping your index between 0 and count - 1 is your job, not the compiler's.

Try it yourself

Edit it. Break it. Run it again.
#include <stdio.h>

int main(void) {
    int scores[4] = {70, 85, 90, 64};
    int count = sizeof(scores) / sizeof(scores[0]);

    printf("the array uses %zu bytes for %d ints\n", sizeof(scores), count);
    for (int i = 0; i < count; i++) {
        printf("scores[%d] = %d, %d bytes from the start\n", i, scores[i], i * (int)sizeof(int));
    }
    return 0;
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Sum and max

Given the array in the starter, loop over it and print its total and its largest value:

  • total: 291
  • max: 93
#include <stdio.h>

int main(void) {
    int temps[6] = {41, 17, 93, 56, 38, 46};
    int total = 0;
    int max = 0;

    printf("total: %d\n", total);
    printf("max: %d\n", max);
    return 0;
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Backwards

Print the elements of the array in reverse order, separated by single spaces, on one line, then a newline: 50 40 30 20 10 Use the sizeof trick to get the count instead of typing 5.

#include <stdio.h>

int main(void) {
    int nums[] = {10, 20, 30, 40, 50};
    int count = 0;

    for (int i = 0; i < count; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");
    return 0;
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.