Dynamic and Heterogeneous Vectors in C

std::vector is a very useful container with dynamic resizing upon insertion and deletion. I wanted to understand how it worked better, so I decided to implement it in C. Furthermore, I wanted to make it so that I can store multiple data types, kind of like a Python List.

TL;DR of how and what I implemented:

Tagged unions

typedef enum tag {
    BOOL,
    CHAR,
    INT,
    FLOAT,
    DOUBLE,
    STRING,
    ANY
} Tag;

typedef struct {
    enum tag tag;
    union {
        bool b;
        char c;
        int i;
        float f;
        double d;
        String s;
    } value;
} Dynamic;

(The String datatype is my implementation of string views following Tsoding's C strings stream, but ignore that part. Just thought I'd mention it once since it may show up in the code later.)

So a tagged union. It's a nice way to get dynamic typing in C if you're not strapped for memory.

Dynamic integer = (Dynamic) { .tag = INT, .value.i = 10.10 };
// this will explicitly store 10 as an integer, ignoring the floating part
integer.tag = FLOAT;
// this will return 1092721050 when printed 
// because the value was not stored as a float 
// floats use IEEE 754 to store their values
// It tried to interpret the underlying memory as described in IEEE 754 and got this result

1. Printing this would require a function such as this

void Generic_printer(Dynamic element) 
{

    switch (element.tag) {
        case BOOL: 
            printf("%s", (element.value.b)?"true":"false" );
            break;
        case CHAR:
            printf("%c", element.value.c);
            break;
        case FLOAT: 
            printf("%f", (element.value.f));
            break;
        case DOUBLE:
            printf("%lf", (element.value.d));
            break;
        case INT: 
            printf("%i", (element.value.i));
            break;
        case STRING:
            String_print(&element.value.s);
            break;
        case ANY:
            break;
    }
    
}

2. Comparer

Now this is a strange function. But it's useful for a multitude of other functions that use it. All it does is:

int Tagged_comparer(const void *a, const void *b) 
{
    Dynamic arg1 = *(const Dynamic *)a;
    Dynamic arg2 = *(const Dynamic *)b;
    Tag tag = arg1.tag;
    
    switch (tag) {
        case BOOL: 
            if (arg1.value.b < arg2.value.b) return -1;
            if (arg1.value.b > arg2.value.b) return 1;
            break;
        case CHAR:
            if (arg1.value.c < arg2.value.c) return -1;
            if (arg1.value.c > arg2.value.c) return 1;
            break;
        case FLOAT: 
            if (arg1.value.f < arg2.value.f) return -1;
            if (arg1.value.f > arg2.value.f) return 1;
            break;
        case DOUBLE:
            if (arg1.value.d < arg2.value.d) return -1;
            if (arg1.value.d > arg2.value.d) return 1;
            break;
        case INT: 
            if (arg1.value.i < arg2.value.i) return -1;
            if (arg1.value.i > arg2.value.i) return 1;
            break;
        case STRING:
        case ANY:
            break;
    }


    return 0;
}

Now we have a dynamic typing system in place. Let's move on to making a vector!

Vector

typedef struct vector {
    Dynamic *vector;
    size_t counter;
    size_t size;
    Tag type;
    bool isSorted;
} Vector;

1. Let's create and free the vector first

Vector *Vector_create(size_t size, Tag type)
// function returns a pointer to a Vector
// with the specific size and type
{
    Vector *v = malloc(sizeof(Vector));
    // allocate memory size of a vector

    v->size = size;
    // total size given by the user
    
    v->counter = 0;
    // since no places are filled
    
    v->type = type;
    // type given by the user
    
    v->isSorted = false;
    // is not sorted by default
    
    v->vector = calloc(v->size, sizeof(Dynamic));
    // allocates memory for v->size elements of type Dynamic

    return v;
}


void Vector_dealloc(Vector *v)
{
    free(v->vector);
    // free the allocated memory internally first
    
    free(v);
    // free the vector
}

2. Pushing and popping elements from the back

void Vector_pushBack(Vector *v, Dynamic element) 
{
    if (v->type != element.tag && v->type != ANY) {
        fprintf(stderr, "Tried inserting type %s in vector of type %s\n", Tagged_string(element.tag), Tagged_string(v->type));
        return;
    }

    if (v->counter == v->size) {
        v->size += v->size;
        v->vector = realloc(v->vector, sizeof(Dynamic) * v->size);
    }

    if (v->isSorted && v->counter > 0 && Tagged_comparer(&v->vector[v->counter - 1], &element) > 0) {
        v->isSorted = false;
    }

    v->vector[v->counter] = element;
    v->counter++;
}
Dynamic Vector_popBack(Vector *v) 
{

    if (v->counter == 0) {
        fprintf(stderr, "Vector underflow\n");
        exit(EXIT_FAILURE);
    }

    v->counter--;
    Dynamic element = v->vector[v->counter];

    if (v->counter < (v->size / 2)) {
        v->size /= 2;
        v->vector = realloc(v->vector, sizeof(Dynamic) * v->size);
    }

    return element;
}

3. Sorting the vector and finding elements

Believe it or not, stdlib.h has built-in Quick Sort and Binary Search. It is the reason why we had to write the Tagged_comparer in the first place.

void Vector_sort(Vector *v)
{
    if (v->type == ANY || v->type == STRING) {
        fprintf(stderr, "Can't sort vector of type %s\n", Tagged_string(v->type));
        return;
    }

    if (v->isSorted) {
        fprintf(stderr, "Already sorted\n");
        return;
    }

    qsort(v->vector, v->counter, sizeof(Dynamic), Tagged_comparer);
    v->isSorted = true;

}

And for the searching part

Dynamic *Vector_findElement(Vector *v, Dynamic target)
{
    if (!v->isSorted) {
        fprintf(stderr, "Error: Vector must be sorted before performing binary search.\n");
        exit(EXIT_FAILURE);
    }

    // if null then doesn't exist
    return bsearch(&target, v->vector, v->counter, sizeof(Dynamic), Tagged_comparer);
}

int Vector_findIndex(Vector *v, Dynamic target)
{
    Dynamic *result = Vector_findElement(v, target);
    if (result == NULL) {
        return -1;
    }
    // Calculate index using pointer arithmetic
    return (int)(result - v->vector);
}

And there we have it. A dynamic, heterogeneous vector in C.