All Topics
All Topics
Technology
Technology
Design
Design
Programming
Programming
Science
Science
News
News
Gaming
Gaming
Entertainment
Entertainment
Business
Business
Finance
Finance
Sports
Sports
Health
Health
Food
Food
Travel
Travel
Art
Art
Music
Music
Books
Books
Education
Education
Politics
Politics
Personal
Personal
No algorithm. No AI slop. No ads. Just RSS. Pro-human. Indie writers. Real journalism. Open web. Chronological. Hand toasted.

Generic dynamic array in C using two pointers, no struct required

By

262588213843476

4h ago· 2 min readenCode

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 pulled
int *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).
Snippet from the RSS feed
A generic dynamic array in C that stores no capacity and needs no struct - README.md

You might also wanna read