Data Structures

Data Structures#

C has a small core (arrays, structs, unions, pointers) on which everything else is built.

Arrays#

Fixed-length, contiguous, zero-indexed.

int xs[5] = {1, 2, 3, 4, 5};
size_t n = sizeof xs / sizeof xs[0];   // 5

Arrays decay to pointers when passed to functions; pass the length alongside.

int sum(const int *xs, size_t n) {
    int s = 0;
    for (size_t i = 0; i < n; i++) s += xs[i];
    return s;
}

Structs#

typedef struct {
    char  *name;
    int    age;
} Person;

Person p = { .name = "operator", .age = 36 };

Unions#

A union shares storage between several fields.

typedef union {
    int    as_int;
    float  as_float;
    char   bytes[4];
} Word;

Linked List#

typedef struct Node {
    int          value;
    struct Node *next;
} Node;

Dynamic Array#

A growable array tracks capacity alongside length.

typedef struct {
    int   *data;
    size_t len;
    size_t cap;
} Vec;

void vec_push(Vec *v, int x) {
    if (v->len == v->cap) {
        v->cap = v->cap ? v->cap * 2 : 8;
        v->data = realloc(v->data, v->cap * sizeof *v->data);
    }
    v->data[v->len++] = x;
}