HeadlinesBriefing favicon HeadlinesBriefing.com

Generic Dynamic Array in C Uses Two Pointers Instead of Structs

Hacker News •
×

A minimalist approach to dynamic arrays in C uses just two pointers instead of traditional structs. The implementation stores length in the first pointer and data in the second, eliminating the need for wrapper structures like IntVec. Code example shows `int *vec[2] = { 0 }` creating an empty integer array.

This C23 implementation leverages statement expressions, a GNU C extension, to achieve genericity without macros or void pointers. By casting through uintptr_t, the length travels as a pointer value, though this relies on implementation-defined behavior that may limit portability.

Capacity management takes an unusual approach—instead of tracking it separately, the code computes capacity on demand. When length hits zero or a power of two, realloc allocates the next power-of-two size. This creates a trade-off: manual reservations get discarded during push operations when automatic reallocation occurs.

The technique appeals to developers seeking struct-free collections, but comes with constraints around memory reservation and compiler compatibility. It demonstrates creative problem-solving within C's limitations, though production use requires careful consideration of the portability implications.