initialize dynamic array library with tests and configuration files
This commit is contained in:
76
src/dynamic_array.c
Normal file
76
src/dynamic_array.c
Normal file
@@ -0,0 +1,76 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "dynamic_array.h"
|
||||
|
||||
|
||||
Array *array_builder(const ArrayBuilderOptions *options) {
|
||||
const auto array = (Array*) malloc(sizeof(Array));
|
||||
|
||||
int size = DEFAULT_ARRAY_SIZE;
|
||||
if (options != NULL && options->initial_size > 0) {
|
||||
size = options->initial_size;
|
||||
}
|
||||
array->capacity = size;
|
||||
array->value = (int*) calloc(array->capacity, sizeof(int));
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
void array_deconstructor(Array *array) {
|
||||
if (array == NULL) {
|
||||
return;
|
||||
}
|
||||
free(array->value);
|
||||
free(array);
|
||||
}
|
||||
|
||||
void array_resize(Array *array, const int new_size) {
|
||||
int *new_ptr = (int *) realloc(array->value, new_size*sizeof(int));
|
||||
if (new_ptr == NULL) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (new_size > array->capacity) {
|
||||
memset(new_ptr + array->capacity, 0, (new_size - array->capacity) * sizeof(int));
|
||||
}
|
||||
|
||||
array->value = new_ptr;
|
||||
array->capacity = new_size;
|
||||
}
|
||||
|
||||
int *array_get_value(const Array *array, const int index) {
|
||||
if (index > array->capacity) {
|
||||
return nullptr;
|
||||
}
|
||||
return &array->value[index];
|
||||
}
|
||||
|
||||
void array_set_value(Array *array, const int index, const int value) {
|
||||
if (index > array->capacity) {
|
||||
const int new_size = (index - array->capacity) * 2 + array->capacity;
|
||||
array_resize(array, new_size);
|
||||
}
|
||||
array->value[index] = value;
|
||||
}
|
||||
//
|
||||
// int main() {
|
||||
// Array *a = array_builder();
|
||||
//
|
||||
// int index = 1000;
|
||||
// int expected_value = 99;
|
||||
//
|
||||
// array_set_value(a, index, expected_value);
|
||||
//
|
||||
// int *value = array_get_value(a, index);
|
||||
// if (value != NULL) {
|
||||
// printf("Found the value %d in the index %d of array", *value, index);
|
||||
// } else {
|
||||
// printf("Found invalid index for array");
|
||||
// }
|
||||
//
|
||||
// array_deconstructor(a);
|
||||
//
|
||||
// return 0;
|
||||
// }
|
||||
Reference in New Issue
Block a user