Arrays and pointer arithmetic

Lesson 5 of 14 · C memory foundations

An array holds a fixed number of same-type elements in adjacent storage. Indexing starts at zero. For int a[3] = {4, 8, 12};, valid indices are 0, 1 and 2.

index       0       1       2       one past
          [ 4 ]   [ 8 ]   [ 12 ]       |
a ───────> ^
a + 2 ───────────────────> ^

In most expressions a converts to a pointer to its first element; a[2] is equivalent to *(a + 2). Addition advances in units of the pointed-to type, not single bytes. One-past is allowed to be formed for iteration but not dereferenced. Pointer arithmetic is constrained to the same array and its one-past position. Arrays are not pointers: sizeof a measures the whole array, while sizeof a pointer measures that pointer. In void f(int a[3]), the parameter is adjusted to a pointer, so pass the length separately.

#include <stdio.h>
int main(void) {
    int a[] = {4, 8, 12};
    size_t n = sizeof a / sizeof a[0];
    for (size_t i = 0; i < n; i++) printf("%d\n", a[i]);
    return 0;
}

Output is 4, 8, 12 on separate lines. When passing an array, the pointer is copied, but accesses through the copy still reach the caller’s elements. Array elements may themselves be structs or pointers; an array of pointers stores addresses, not the pointed-to objects. Pointer sizes may differ for different pointer types on a conforming implementation.

Chapter index · Course index