From 40bab5490e727b454c41e1c7cc1d6d2ccffce4db Mon Sep 17 00:00:00 2001 From: lucielle Date: Tue, 9 Jun 2026 07:23:41 -0500 Subject: [PATCH] add dynamic array --- .clangd | 2 ++ .gitignore | 1 + array.h | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ test.c | 41 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 100 insertions(+) create mode 100644 .clangd create mode 100644 .gitignore create mode 100644 array.h create mode 100644 test.c diff --git a/.clangd b/.clangd new file mode 100644 index 0000000..e467247 --- /dev/null +++ b/.clangd @@ -0,0 +1,2 @@ +CompileFlags: + Add: [-xc] \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d163863 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +build/ \ No newline at end of file diff --git a/array.h b/array.h new file mode 100644 index 0000000..8e9d1f0 --- /dev/null +++ b/array.h @@ -0,0 +1,56 @@ +#ifndef LTYPES_ARRAY_H +#define LTYPES_ARRAY_H +#define L_ARRAY_IMPLEMENTATION // for development to fix clangd + +#define L_TYPES_AUTHOR "Lucielle + +typedef struct { + size_t count; + size_t capacity; + void** items; +} l_array; + +l_array* l_array_create(); +void l_array_delete(l_array* array); +int l_array_append(l_array* array, void* item); +void l_array_clear(l_array* array); + +#ifdef L_ARRAY_IMPLEMENTATION + +#include + +l_array* l_array_create() { + return (l_array*) calloc(1, sizeof(l_array)); +} + +void l_array_delete(l_array* array) { + free(array); +} + +int l_array_append(l_array* array, void* item) { + if (array->count >= array->capacity) { + if (array->capacity == 0) array->capacity = 8; + else array->capacity *= 2; + + array->items = realloc(array->items, array->capacity * sizeof(*array->items)); + } + + array->items[array->count++] = item; + return 0; +} + +void l_array_clear(l_array* array) { + free(array->items); + array->items = NULL; + array->capacity = 0; + array->count = 0; +} + +#endif + +#endif \ No newline at end of file diff --git a/test.c b/test.c new file mode 100644 index 0000000..4edbe62 --- /dev/null +++ b/test.c @@ -0,0 +1,41 @@ +#include +#define L_ARRAY_IMPLEMENTATION +#include "array.h" +#include "assert.h" + +#define TEST_FUNCTION + +static int test_l_array() { + int RETURN_CODE = 0; + + l_array* array = l_array_create(); + + int number_1 = 5; + int number_2 = 15; + + l_array_append(array, &number_2); + l_array_append(array, &number_1); + + assert(*(int*)array->items[0] == 15); + assert(*(int*)array->items[1] == 5); + assert(array->count == 2); + assert(array->capacity == 8); + + l_array_clear(array); + assert(array->items == NULL); + + return RETURN_CODE; +} + +int main(void) { + printf("AUTHOR: %s\n", L_TYPES_AUTHOR); + printf("REPO: %s\n", L_TYPES_REPO); + printf("VERSION: %s\n", L_TYPES_VERSION); + printf("LICENSE: %s\n\n", L_TYPES_LICENSE); + + + if ( + test_l_array() + ) return 1; + return 0; +} \ No newline at end of file