CC
BeginnerLesson 7 of 18

Arrays – C

Fixed-size arrays: indexing, initialization, passing to functions and multidimensional arrays.

An array is a fixed number of elements of the same type that lie directly one after another in memory. Indices run from 0 to n-1. The size must be known at compile time (VLAs since C99 are optional and risky).

#include <stdio.h>

double mittelwert(const int a[], size_t n) {
    long summe = 0;
    for (size_t i = 0; i < n; i++) summe += a[i];
    return (double)summe / n;
}

int main(void) {
    int werte[5] = {4, 8, 15, 16, 23};
    size_t n = sizeof werte / sizeof werte[0];
    printf("n=%zu, average=%.1f\n", n, mittelwert(werte, n));

    int nullen[4] = {0};        // all elements 0
    int teil[6] = {1, 2};       // the rest is filled with 0
    printf("%d %d %d\n", nullen[3], teil[1], teil[5]);
    return 0;
}

When passed to a function, the array "decays" into a pointer to its first element – the length is lost. That is why you always pass it as a separate parameter (size_t n). Inside the function, sizeof only returns the size of the pointer!

Multidimensional arrays are arrays of arrays and are stored row by row in memory:

#include <stdio.h>

int main(void) {
    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) printf("%d ", m[i][j]);
        printf("\n");
    }
    return 0;
}
WarningC does not check indices. a[5] for int a[5] reads or overwrites foreign memory – without any error message. This is the cause of countless security vulnerabilities. Check bounds yourself and test with -fsanitize=address.
TipThe pattern sizeof arr / sizeof arr[0] only works where arr really is an array (in the same scope as its declaration), not for function parameters.