diff options
| author | Raghuram Subramani <raghus2247@gmail.com> | 2025-06-19 16:54:34 +0530 |
|---|---|---|
| committer | Raghuram Subramani <raghus2247@gmail.com> | 2025-06-19 16:54:34 +0530 |
| commit | e4c5d83e418f1a045758339779fb49b635db2bdb (patch) | |
| tree | 8fdf2fda83f88a12ab971968eee81a7edf8b48d5 /src | |
| parent | 2ab610ffa95df79dcb3bcea2328b49234c65e372 (diff) | |
(list): add lists
Diffstat (limited to 'src')
| -rw-r--r-- | src/list.c | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/src/list.c b/src/list.c new file mode 100644 index 0000000..1d0549b --- /dev/null +++ b/src/list.c @@ -0,0 +1,57 @@ +#include <list.h> +#include <stddef.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +list_t * +list_create(size_t element_size) +{ + list_t *list = malloc(sizeof(list_t)); + if (list == NULL) + return NULL; + + list->element_size = element_size; + list->size = 0; + list->max = START_SIZE; + list->elements = (uint8_t *) calloc(list->max, element_size); + + return list; +} + +void +list_add(list_t *list, void *element) +{ + if (list->size == list->max) { + list->max += INCREMENT_BY; + list->elements + = (uint8_t *) realloc(list->elements, list->element_size * list->max); + if (list->elements == NULL) { + /* TODO: Handle error */ + printf("Failed to reallocate array\n"); + return; + } + } + + void *new_element = list->elements + list->element_size * list->size; + new_element = memcpy(new_element, element, list->element_size); + + if (new_element == NULL) + printf("Failed to add a new element\n"); + + list->size++; +} + +void * +list_get(list_t *list, size_t i) +{ + return list->elements + (i * list->element_size); +} + +void +list_delete(list_t *list) +{ + free(list->elements); + free(list); +} |
