A no bullshit type-safe vector library for C that supports operator []
for
indexing.
#include "cvec.h"
int *x = NULL; /* initialize to NULL, replace *int* with any type you want */
vector_push(x, 100);
vector_push(x, 200);
vector_push(x, 300);
/* standard [] lookup of values */
printf("%d, %d, %d", x[0], x[1], x[2]);
/* free memory */
vector_free(x);
Metadata of a vector is stored as a header behind the pointer exactly
sizeof(vector_t)
behind. This is how operator []
can still be used for
indexing. Type safety is provided by having the pointer encode the type
via the language itself. No strange void*
tricks. Though the generic resize
functions sort of cast to void*
but that is standard practice in C.
Note that VECTOR
is any pointer type and that the API is mostly implemented
using macros. The macros all take VECTOR
argument, size and indexing
arguments are expected to be size_t
. The macros which push back a value
expect the pointer's base type.
Attempts to grow VECTOR
by MORE
Get the metadata block for VECTOR
Deletes VECTOR
and sets it to NULL
Pushes back VALUE
into VECTOR
Get the size of VECTOR
Get the capacity of VECTOR
Resize VECTOR
to accomodate SIZE
more elements
Get the last element in VECTOR
Pop an element off the back of VECTOR
Shrink the size of VECTOR
down to SIZE
Shrink VECTOR
down by AMOUNT
Append to VECTOR
, COUNT
elements from POINTER
Remove from VECTOR
, COUNT
elements starting from INDEX