single-header library providing nice generic slices in C.
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-08-16 08:25:30 +09:30
README.md Initial commit 2026-08-16 08:25:30 +09:30
slc.h Initial commit 2026-08-16 08:25:30 +09:30

slc

single-header library providing nice generic slices in C. essentially copies Go's slice semantics, but uses that funky negative indexing trick to make it appear like a regular array.

because of this, slicing a slice actually allocates and returns a copy of it. if you don't want this, you can just use it like a regular array, and only use the slice semantics when convenient.

usage

example using slc_nmake, constructing a slice from a pre-existing buffer:

char* s = slc_nmake("hello", sizeof("hello"), sizeof(char));

// prints all characters in slice s
for (int i = 0; i < slc_len(s); i++) {
  printf("character at %d is %c\n", i, s[i]);
}

example using slc_make, constructing a slice from an initial capacity and element size:

char* s = slc_make(5, sizeof(char));

// the following won't do any heap allocations,
// since the capacity has not yet been reached.
// if it did reallocate, s would be reassigned.
s = slc_append(s, (char[]){'h'});
s = slc_appendn(s, (char[]){"ello"}, 4);

// prints all characters in slice s
for (int i = 0; i < slc_len(s); i++) {
  printf("character at %d is %c\n", i, s[i]);
}

example using slc_zero to zero a range of indices in a slice:

// zeroes all elements in the half-open range [0, 5)
slc_zero(s, 0, 5);

example using slc_slice/slc_dup to create a partial/full copy of a slice:

// creates a copy of a with the half-open range [2, 4)
b = slc_slice(a, 2, 4);
slc_free(b); // b is a separate object, so it still has to be freed

// creates a duplicate of a
b = slc_dup(a);