Learn C
#include "systems/dynamic_array.h"

Capstone: Dynamic Array in C

#concept

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.

#how it works
1

Track trio: data, size, capacity

struct Vec { int *data; size_t size, cap; }; — size counts live elements, cap counts allocated slots, size <= cap always.

2

Double on full

Full means size == cap: realloc to 2x (from a nonzero seed) — geometric growth amortizes to O(1) per push.

3

Realloc through temporaries

Growth failure must preserve the old buffer — temporary-pointer protocol or the array leaks on the error path.

4

Destroy completely

vec_free frees data and zeroes the struct — use-after-free becomes a loud null crash instead of silent corruption.

#example
#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;
}
Output
2 2
1{0} zeroes the struct — NULL data, empty, zero capacity, ready for first growth.
2First push grows to 4 slots via realloc-through-temporary; both appends land without further growth.
3size 2 and second element 2 print — vector semantics hand-rolled from course primitives.
#complexity
time O(1) amortized push
space O(n)

Doubling wastes at most half capacity; indexed access stays O(1).

#use cases
Growing buffers (lines, tokens, results) without fixed caps
Amortized O(1) appends via geometric growth
Reusable container pattern for every element type (via macros or void*)
Freeing completely with struct reset against use-after-free

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.