add dynamic array

This commit is contained in:
2026-06-09 07:23:41 -05:00
parent 0bc769bccd
commit 40bab5490e
4 changed files with 100 additions and 0 deletions

2
.clangd Normal file
View File

@@ -0,0 +1,2 @@
CompileFlags:
Add: [-xc]

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
build/

56
array.h Normal file
View File

@@ -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 <luci@git.lunarware.tech"
#define L_TYPES_REPO "https://git.lunarware.tech/lucielle/ltypes.git"
#define L_TYPES_VERSION "0.1.0"
#define L_TYPES_LICENSE "GNU GPL v3"
#include <stddef.h>
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 <stdlib.h>
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

41
test.c Normal file
View File

@@ -0,0 +1,41 @@
#include <stdio.h>
#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;
}