From daad1e7e3abf5a27a41d8b5e52a4536068030327 Mon Sep 17 00:00:00 2001 From: Vincent Douillet Date: Tue, 7 Dec 2021 18:13:24 +0100 Subject: day 6 --- list.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 list.c (limited to 'list.c') diff --git a/list.c b/list.c new file mode 100644 index 0000000..6001424 --- /dev/null +++ b/list.c @@ -0,0 +1,46 @@ +#include +#include "list.h" + +#define LIST_SIZE 50 + +struct long_list* long_list_init(size_t size) { + struct long_list* list = malloc(sizeof(struct long_list)); + list->list = malloc(sizeof(long) * size); + list->alloc_size = size; + list->length = 0; + return list; +} + +void long_list_free(struct long_list* list) { + if(list == NULL) + return; + + if(list->list != NULL) + free(list->list); + + free(list); +} + +void long_list_add(struct long_list* list, long value) { + // increase space if needed + if(list->length >= list->alloc_size) { + list->list = realloc(list->list, sizeof(long) * (list->alloc_size + LIST_SIZE)); + list->alloc_size += LIST_SIZE; + } + list->list[list->length] = value; + list->length = list->length + 1; +} + +long long_list_get(struct long_list* list, size_t index) { + if(index >= list->length) + err(1, "index %ld out of bounds (%ld)", index, list->length); + + return list->list[index]; +} + +void long_list_set(struct long_list* list, size_t index, long value) { + if(index >= list->length) + err(1, "index %ld out of bounds (%ld)", index, list->length); + + list->list[index] = value; +} -- cgit v1.2.3