A dynamic array (vector) tracks a size (items stored) and a capacity (slots allocated). When full, it calls realloc to double the capacity, which makes appending amortized O(1). Bundle the pointer, size, and capacity in a struct.
Keep these facts handy while you work with Dynamic Arrays in C.
Topic
Detail
size
Elements currently stored
capacity
Slots allocated
Growth
Double on full
Append cost
Amortized O(1)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Dynamic 2D Arrays.
Example 1 — Append values and grow automatically
Start with capacity 2 and push five values.
C
#include <stdio.h>
#include <stdlib.h>
struct Vec { int *data; size_t size, cap; };
static int push(struct Vec *v, int value) {
if (v->size == v->cap) {
size_t ncap = v->cap * 2;
int *tmp = realloc(v->data, ncap * sizeof *tmp);
if (!tmp) return 0;
v->data = tmp;
v->cap = ncap;
}
v->data[v->size++] = value;
return 1;
}
int main(void) {
struct Vec v = { malloc(2 * sizeof(int)), 0, 2 };
if (!v.data) return 1;
for (int i = 1; i <= 5; i++) push(&v, i);
for (size_t i = 0; i < v.size; i++) printf("%d ", v.data[i]);
printf("\nsize=%zu capacity=%zu\n", v.size, v.cap);
free(v.data);
return 0;
}
Output
1 2 3 4 5
size=5 capacity=8
How It Works
Capacity grows 2, 4, 8 as items 3 and 5 arrive.
push returns 0 if reallocation fails.
Doubling spreads the copy cost across many appends.
Edge Cases & Pitfalls
Check these before relying on Dynamic Arrays in real programs.
cap0
Starting at capacity 0
Doubling 0 stays 0. Start at a positive capacity or use cap ? cap * 2 : 4.
ptr
Pointers into data
Pointers to elements dangle when realloc moves the block. Store indexes instead.
Remember
Key Takeaways
Track: size and capacity.
Double: amortized O(1).
Free: release data at the end.
One line: A dynamic array (vector) tracks a size (items stored) and a capacity (slots allocated).
Frequently Asked Questions
Growing by a constant factor copies elements far less often. Adding one each time copies the whole array on every append, making n appends O(n^2).
No. You build one with malloc and realloc, or use a library.
Continue with "C Dynamic 2D Arrays" next. Allocate a matrix of rows and columns on the heap. The C Dynamic Memory Allocation hub lists every topic in order.