C vec implementation

Anonymous
c_cpp
04/19/2026 6:42 PM
1.4 KB
17
Indexable
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct
{
    size_t length;
    size_t capacity;
    size_t elem_size;
    void *data;
} Vec;

void vec_init(Vec *v, size_t elem_size)
{
    *v = (Vec){
        .length = 0,
        .capacity = 1,
        .elem_size = elem_size,
        .data = NULL};
    v->data = malloc(v->capacity * v->elem_size);
}

void vec_push(Vec *v, void *value)
{
    if (v->length >= v->capacity)
    {
        printf("Resized\n");
        v->capacity *= 2;
        v->data = realloc(v->data, v->capacity * v->elem_size);
    }
    char *ptr = (char *)v->data + v->length * v->elem_size;
    memcpy(ptr, value, v->elem_size);
    v->length++;
}

int main(int argc, char *argv[])
{
    Vec vec_int;
    vec_init(&vec_int, sizeof(int));
    // int value = 0;
    // vec_push(&vec_int, &value);
    for (int i = 1; i <= 20; i++)
    {
        int value = i;
        vec_push(&vec_int, &value);
    }

    for (int i = 0; i < vec_int.length; ++i)
    {
        printf("%d\n", *((int *)vec_int.data + i));
    }
    return 0;
}
Editor is loading...
Leave a Comment