Capstone: Dynamic Array in C
A dynamic array (vector) distills half the course into one structure: a struct holding data pointer, size, and capacity, with push doubling capacity via realloc when full. It exercises structs, pointers, malloc/realloc discipline, amortized analysis (doubling keeps push O(1) amortized), and header/implementation separation in a single weekend-sized project.
The protocol: init (NULL data, 0/0), push (grow-if-full then append), get with bounds asserts, pop, and destroy (free + reset). Every systems program eventually grows one — now it is yours, understood to the last byte.
Track trio: data, size, capacity
struct Vec { int *data; size_t size, cap; }; — size counts live elements, cap counts allocated slots, size <= cap always.
Double on full
Full means size == cap: realloc to 2x (from a nonzero seed) — geometric growth amortizes to O(1) per push.
Realloc through temporaries
Growth failure must preserve the old buffer — temporary-pointer protocol or the array leaks on the error path.
Destroy completely
vec_free frees data and zeroes the struct — use-after-free becomes a loud null crash instead of silent corruption.
#include <stdio.h>#include <stdlib.h> typedef struct { int *data; size_t size, cap; } Vec; void push(Vec *v, int x) { if (v->size == v->cap) { size_t ncap = v->cap ? v->cap * 2 : 4; int *t = realloc(v->data, ncap * sizeof *t); if (!t) return; v->data = t; v->cap = ncap; } v->data[v->size++] = x;} int main(void) { Vec v = {0}; push(&v, 1); push(&v, 2); printf("%zu %d\n", v.size, v.data[1]); free(v.data); return 0;}Doubling wastes at most half capacity; indexed access stays O(1).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.