Skip to content

Instantly share code, notes, and snippets.

View alurm's full-sized avatar

Alan Urmancheev alurm

View GitHub Profile
@alurm
alurm / README.md
Last active June 17, 2026 04:37
A generic dynamic array in C that stores no capacity and needs no struct

A generic dynamic array in C that stores no capacity and needs no struct

The following header shows a way to make a generic dynamic array in C with an array of two pointers:

  • one pointer (accessible as vec_ptr[vec]) points to the data;
  • the other pointer (accessible as vec_len[vec]) encodes the length of the array in the pointer. Thus, (size_t)vec_len[vec] returns the len as size_t.

So, int *vec[2] = { 0 }; is an empty dynamic array of ints. struct person *people[2] = { 0 }; is an empty dynamic array of people.

The vec_push(vec, value) macro pushes a value at the end of a dynamic array. It returns true if pushing succeeded, and false otherwise. Note that the dynamic array is not automatically freed on failure.