C Arrays

C arrays store several values of the same type in one contiguous block of memory. Instead of making ten separate variables, you make one array with ten elements and access each by its index.

Declaring and Accessing Arrays

Indexes start at 0, so the last element of a 5-element array is at index 4.

#include <stdio.h>

int main(void) {
    int scores[5] = {80, 92, 67, 75, 88};
    printf("First: %d\n", scores[0]);
    scores[2] = 70;   // change an element
    printf("Third: %d\n", scores[2]);
    return 0;
}
First: 80
Third: 70

Looping Through an Array and Getting Its Length

sizeof the whole array divided by sizeof one element gives the number of elements. This only works where the array itself is in scope, not on a pointer.

#include <stdio.h>

int main(void) {
    double prices[] = {2.5, 4.0, 1.25, 3.75};
    size_t n = sizeof prices / sizeof prices[0];
    double total = 0;
    for (size_t i = 0; i < n; i++) {
        total += prices[i];
    }
    printf("%zu items, total %.2f\n", n, total);
    return 0;
}
4 items, total 11.50

Passing Arrays to Functions

When passed to a function, an array becomes a pointer to its first element, so you must pass the length separately.

#include <stdio.h>

int findMax(const int arr[], size_t len) {
    int max = arr[0];
    for (size_t i = 1; i < len; i++)
        if (arr[i] > max) max = arr[i];
    return max;
}

int main(void) {
    int nums[] = {4, 19, 7, 12};
    printf("Max: %d\n", findMax(nums, 4));
    return 0;
}
Max: 19

Two-Dimensional Arrays

#include <stdio.h>

int main(void) {
    int grid[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) printf("%d ", grid[r][c]);
        printf("\n");
    }
    return 0;
}
1 2 3
4 5 6 

Array Safety

  • C does not check array bounds: reading arr[10] in a 5-element array is undefined behavior.
  • The size of a normal array is fixed once declared.
  • For a size chosen at runtime, use malloc (see the memory lesson).

Frequently asked questions

How do I find the length of an array in C?

Use sizeof arr / sizeof arr[0] in the same scope where the array is declared. Inside a function that received the array as a parameter, this does not work, so pass the length as an extra argument.

Why do C arrays start at index 0?

The index is an offset from the start of the array in memory. The first element is zero elements away from the start.

What happens if I access an array out of bounds in C?

C does not stop you. The result is undefined behavior: you may read garbage, corrupt other variables or crash the program.