C/C++ Arena

Arrays in C

Declaring, indexing and looping over arrays in C, 2D arrays, and why arrays passed to functions lose their size.

An array is a fixed number of elements of one type, stored side by side. Indexes start at 0, so an array of 5 has indexes 0 to 4. C doesn't check indexes: reading a[5] is undefined behavior, not an error message.

sizeof a / sizeof a[0] gives the element count, but only where the array was declared. When you pass an array to a function it turns into a pointer to its first element, so pass the length as a separate parameter.

A 2D array like int grid[3][4] is 3 rows of 4 ints.

Example

#include <stdio.h>

int total(const int a[], int n) {
    int t = 0;
    for (int i = 0; i < n; i++) t += a[i];
    return t;
}

int main(void) {
    int scores[] = {90, 72, 85};
    int n = sizeof scores / sizeof scores[0];
    printf("%d scores, total %d\n", n, total(scores, n));
    return 0;
}

Output:

3 scores, total 247

Watch it run: An array is a row of boxes

Practice it