rxi/vec - a simple C vector library

C provides arrays, but these do less than most other languages’ array structures. For instance, if you want to push a new element onto the end of your array, you must go through the work of resizing it with realloc to make room for the new element. For this, you need to keep track of the array length separately. Then to avoid constant reallocation you keep a separate length and capacity. Soon you’ve written a vector library.

Instead, you can use someone else’s vector library. I like rxi/vec. Here’s an example of using it. Installation:

$ brew install clib
$ clib install rxi/vec
$ find .

Example program:

#include <stdio.h>
#include "./deps/vec/vec.h"
typedef vec_t(char*) vec_string_t;
void print_vec(vec_string_t * strings) {
  size_t i; char * string;
  vec_foreach(strings, string, i) {
    printf("strings[%zu] = \"%s\"\n", i, string);
int main() {
  vec_string_t strings;
  vec_init(&strings);  // memset(&strings, 0, sizeof(strings));
  vec_push(&strings, "hello");
  vec_push(&strings, "world");
  char* world = vec_pop(&strings);
  printf("popped %s\n", world);
  return 0;

Running it gives:

$ clang main.c deps/vec/vec.c
$ ./a.out
strings[0] = "hello"
strings[1] = "world"
popped world
strings[0] = "hello"

In a future post, I’ll show how rxi/vec is implemented.

I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.