Tuna Gül

Systems

vector-h Archive

A generic vector for C89, built from macros: one line declares a typed vector with its functions, sorting and searching included.

Role
Author
Period
Mar 2021
Team
Solo
Stack
C89

Code ↗cygnus ↗

Illustration of a C vector's memory: older buffers of 2, 4 and 8 slots drawn as freed dashed outlines, each reallocated at double size into the live 16-slot buffer, and a small struct of three pointers below whose coloured arrows mark the buffer's start, the end of the used part and the end of capacity.

What I did

C has no generic containers, so I wrote one with the preprocessor. create_vector_t(int, vector_int_t); generates the struct and every function for that element type; it works for your own structs too.

How it works

  • Functions for init, push back, insert, get, copy, move, reverse, shift and swap. When the vector is full, its capacity doubles with realloc.
  • Bubble sort, merge sort, linear search and binary search. They take a comparison function for the element type, so the same code sorts anything.
  • Unit tests for both versions of the library.
  • Soon after I started cygnus, an N-dimensional matrix in the same macro style, and stopped after shape and storage.
#include "vector.h"

create_vector_t(int, vector_int_t);

int main() {
    vector_int_t v = vector_int_t_init(10);   /* room for 10 ints */
    vector_int_t_push_back(&v, 20);
    printf("%d\n", *vector_int_t_get(&v, 0));
    return 0;
}