Learn more about Russian war crimes in Ukraine.

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.

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

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