refactor dynamic array: enhance element size handling, update memory management, and improve API functions
This commit is contained in:
@@ -7,10 +7,12 @@
|
||||
|
||||
Array *array_create(const ArrayCreateOptions *options) {
|
||||
const ArrayCreateOptions opt = options != NULL ? *options : DEFAULT_ARRAY_CREATE_OPTIONS;
|
||||
Array *array = (Array*) malloc(sizeof(Array));
|
||||
Array *array = malloc(sizeof(Array));
|
||||
|
||||
array->capacity = opt.initial_size;
|
||||
array->value = (int*) calloc(array->capacity, sizeof(int));
|
||||
array->value = calloc(array->capacity, opt.element_size);
|
||||
array->size = 0;
|
||||
array->element_size = opt.element_size;
|
||||
|
||||
return array;
|
||||
}
|
||||
@@ -24,27 +26,27 @@ void array_deconstructor(Array **pp_array) {
|
||||
}
|
||||
|
||||
void array_resize(Array *p_array, const int new_size) {
|
||||
int *new_ptr = realloc(p_array->value, new_size*sizeof(int));
|
||||
int *new_ptr = realloc(p_array->value, new_size*p_array->element_size);
|
||||
if (new_ptr == NULL) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (new_size > p_array->capacity) {
|
||||
memset(new_ptr + p_array->capacity, 0, (new_size - p_array->capacity) * sizeof(int));
|
||||
memset(new_ptr + p_array->capacity, 0, (new_size - p_array->capacity) * p_array->element_size);
|
||||
}
|
||||
|
||||
p_array->value = new_ptr;
|
||||
p_array->capacity = new_size;
|
||||
}
|
||||
|
||||
int *array_get_value(const Array *array, const int index) {
|
||||
if (index > array->capacity) {
|
||||
void *array_get_value(const Array *p_array, const int index) {
|
||||
if (index > p_array->capacity) {
|
||||
return NULL;
|
||||
}
|
||||
return &array->value[index];
|
||||
return p_array->value + index * p_array->element_size;
|
||||
}
|
||||
|
||||
void array_set_value(Array *p_array, const int index, const int value) {
|
||||
void array_set_value(Array *p_array, const int index, const void *value) {
|
||||
if (index > p_array->capacity) {
|
||||
int new_size = p_array->capacity;
|
||||
while (index >= new_size) {
|
||||
@@ -52,10 +54,12 @@ void array_set_value(Array *p_array, const int index, const int value) {
|
||||
}
|
||||
array_resize(p_array, new_size);
|
||||
}
|
||||
memcpy(
|
||||
array_get_value(p_array, index), value, p_array->element_size
|
||||
);
|
||||
if (index >= p_array->size) {
|
||||
p_array->size = index + 1;
|
||||
}
|
||||
p_array->value[index] = value;
|
||||
}
|
||||
|
||||
int array_get_size(const Array *p_array) {
|
||||
|
||||
Reference in New Issue
Block a user