diff options
author | Preston Pan <ret2pop@gmail.com> | 2024-12-24 21:11:06 -0800 |
---|---|---|
committer | Preston Pan <ret2pop@gmail.com> | 2024-12-24 21:11:06 -0800 |
commit | e75d6f6b8f4512a5bbfecbfa8c17f0bb687e3d55 (patch) | |
tree | 7a96002751a1ca3b173762a13b181ebea4123817 /src/array.c |
first commit
Diffstat (limited to 'src/array.c')
-rw-r--r-- | src/array.c | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/array.c b/src/array.c new file mode 100644 index 0000000..84ed938 --- /dev/null +++ b/src/array.c @@ -0,0 +1,37 @@ +#include <array.h> +#include <helpers.h> +#include <stdlib.h> + +array_t *init_array() { + array_t *a = safe_calloc(1, sizeof(array_t)); + a->capacity = DEFAULT_ARR_LEN; + a->size = 0; + a->items = safe_calloc(a->capacity, sizeof(void *)); + return a; +} + +void array_push(array_t *a, void *item) { + if (a->size >= a->capacity - 2) { + a->capacity *= 2; + a->items = realloc(a->items, a->capacity); + } + a->items[a->size] = item; + a->size++; +} + +void *array_pop(array_t *a) { + if (a->size <= 0) + return NULL; + void *retval = a->items[a->size]; + a->size--; + return retval; +} + +void array_free(void *x, void (*freefunc)(void *)) { + array_t *a = (array_t *)x; + for (int i = 0; i < a->size; i++) { + freefunc(a->items[i]); + } + free(a->items); + free(a); +} |