Skip to content

Instantly share code, notes, and snippets.

@Stupremee
Created October 26, 2020 20:19
Show Gist options
  • Save Stupremee/3f42a44481416f4c8a3ae03c50f82fe4 to your computer and use it in GitHub Desktop.
Save Stupremee/3f42a44481416f4c8a3ae03c50f82fe4 to your computer and use it in GitHub Desktop.
List implementation in C
#include "testlib.h"
#include <stdlib.h>
#include <stddef.h>
#include <inttypes.h>
typedef struct vec {
void **data;
uint32_t len;
uint32_t cap;
} vec;
vec *vec_new() {
vec *v = (vec *) malloc(sizeof(vec));
v->data = NULL;
v->len = 0;
v->cap = 0;
return v;
}
void vec_grow(vec *v) {
if (v->cap == 0) {
// i dont care about errors here
v->data = malloc(sizeof( void* ));
v->cap = 1;
} else {
v->cap = v->cap * 2;
// i dont care about errors here
v->data = realloc(v->data, v->cap * sizeof(void *));
}
}
void vec_push(vec *v, void *data) {
if (v->len == v->cap) {
vec_grow(v);
}
v->data[v->len] = data;
v->len += 1;
}
void *vec_pop(vec *v) {
if (v->len == 0) {
return NULL;
}
v->len -= 1;
return v->data[v->len];
}
void vec_free(vec *v) {
free(v->data);
free(v);
}
int main() {
test_start("vec");
vec *v = vec_new();
test_equals_int(0, v->len, "len has to be zero");
int elem = 5;
vec_push(v, &elem);
test_equals_int(1, v->len, "len has to be one");
test_equals_int(elem, *(int *)vec_pop(v), "elem must match");
vec_push(v, &elem);
vec_push(v, &elem);
vec_push(v, &elem);
vec_push(v, &elem);
vec_push(v, &elem);
vec_push(v, &elem);
test_equals_int(6, v->len, "len has to be 6");
vec_free(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment