Skip to content
Guest
Learn C · Course Syllabus Show lessons
Modular C · 9 min read · Intermediate

Dynamic Arrays & realloc

Build a growable dynamic array in C using capacity doubling, realloc(), and leak-free cleanup.

What you'll learn

  • Track both len (used elements) and cap (allocated capacity) in a dynamic array struct
  • Resize heap buffers safely with realloc() using a temporary pointer
  • Understand why doubling capacity gives amortized O(1) appends

Because C does not include a built-in std::vector, building a lightweight dynamic array (data, len, cap) is a classic systems skill. Doubling capacity whenever len == cap makes appending amortized $O(1)$.

Fill-in-the-Blank Exercise

Safe realloc Pattern

Grow buf using a temporary pointer tmp before reassigning buf.

int *tmp = (buf, new_cap * sizeof(int));
if (tmp != ) {
  buf = tmp;
}

Live Code Lab

Cdynarray.c
Expected OutputClick “Run Live” to compile with GCC 13 (C11)
len=5 cap=8 last=50

Check Your Understanding

Score: 0 / 1

1. Why should realloc() results be assigned to a temporary pointer first?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind