#include "array.h" #include #define DEFAULT_ARRAY_SIZE 16 struct ARRAY { void** data; size_t count; size_t size; }; array_t* array_alloc() { array_t* tr = malloc(sizeof(array_t)); tr->data = malloc(sizeof(void*) * DEFAULT_ARRAY_SIZE); tr->size = DEFAULT_ARRAY_SIZE; tr->count = 0; return tr; } void array_free(array_t* array) { free(array->data); free(array); } void array_put(array_t* array, size_t index, void* elem) { // Make sure allocated space is big enough if(index >= array->size) { array->data = realloc(array->data, (index + 1) * 2 * sizeof(void*)); if(!array->data) { perror("Catastrophic memory allocation failure:"); exit(EXIT_FAILURE); } array->size = (index + 1) * 2; } // Put element in array array->data[index] = elem; // Update array count (max element position) if necessary if(array->count <= index) array->count = index + 1; } void array_add(array_t* array, void* elem) { array_put(array, array->count, elem); } void* array_get(array_t* array, size_t index) { if(index >= array->size) { fprintf(stderr, "Catastrophic memory access failure: Trying to access index %lu of %lu-sized array\n", index, array->size); exit(EXIT_FAILURE); } if(index >= array->count) { fprintf(stderr, "Warning: Trying to access index %lu of array with %lu element, uninitialized access\n", index, array->count); } return array->data[index]; } size_t array_count(array_t* array) { return array->count; }