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 assize_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.