Generic dynamic array in C using two pointers, no struct required
By
262588213843476
4h ago· 2 min readenCode
65/100
Toasty
Bagelometer↗
Toasted just enough. A reliable bake, gently seasoned.
Score65Typehow-toSentimentneutral
Summary
This article presents a technique for implementing a generic dynamic array in C using an array of two pointers instead of a struct. The first pointer stores the length (via uintptr_t casting) and the second stores the actual array data. The approach uses C23 with GNU C statement expressions and a vec_push macro. The key advantage is avoiding the need to define named struct types for each element type (e.g., no IntVec, PersonVec, etc.), making the code more generic and reusable.
Key quotes
· 4 pulledint *vec[2] = { 0 }; is an empty dynamic array of ints.
(uintptr_t)vec[0] is the length of the array, vec[1] is the array.
The vec_push macro pushes a value at the end of the dynamic array and returns true on success.
structs aren't used so you don't have to invent names for them (e.g. there is no IntVec).
A generic dynamic array in C that stores no capacity and needs no struct - README.md
