refactor dynamic array: update C standard, improve memory management, and add size/capacity functions

This commit is contained in:
2026-03-26 17:36:39 -03:00
parent a45a74ddff
commit e86a0af333
4 changed files with 278 additions and 8 deletions

View File

@@ -7,7 +7,7 @@
Array *array_create(const ArrayCreateOptions *options) {
const ArrayCreateOptions opt = options != NULL ? *options : DEFAULT_ARRAY_CREATE_OPTIONS;
const auto array = (Array*) malloc(sizeof(Array));
Array *array = (Array*) malloc(sizeof(Array));
array->capacity = opt.initial_size;
array->value = (int*) calloc(array->capacity, sizeof(int));
@@ -20,7 +20,7 @@ void array_deconstructor(Array **pp_array) {
free((*pp_array)->value);
free(*pp_array);
*pp_array = nullptr;
*pp_array = NULL;
}
void array_resize(Array *p_array, const int new_size) {
@@ -39,15 +39,29 @@ void array_resize(Array *p_array, const int new_size) {
int *array_get_value(const Array *array, const int index) {
if (index > array->capacity) {
return nullptr;
return NULL;
}
return &array->value[index];
}
void array_set_value(Array *p_array, const int index, const int value) {
if (index > p_array->capacity) {
const int new_size = (index - p_array->capacity) * 2 + p_array->capacity;
int new_size = p_array->capacity;
while (index >= new_size) {
new_size *= 2;
}
array_resize(p_array, new_size);
}
if (index >= p_array->size) {
p_array->size = index + 1;
}
p_array->value[index] = value;
}
int array_get_size(const Array *p_array) {
return p_array->size;
}
int array_get_capacity(const Array *p_array) {
return p_array->capacity;
}