#ifndef ARRAY_H #define ARRAY_H #include /* Arreglo (vector): region continua de memoria que almacena valores del mismo tipo Registro de memoria (record): region continua de memoria que puede almacenar valores (campos) de diferente tipo. No es Registro de CPU (register) Subrutina: region continua de memoria que almacena instrucciones que pueden ser ejecutadas (invocadas, llamadas) */ /** * @brief * */ // template template struct array_t { /** * @brief * */ size_t count; size_t capacity; DataType* elements; }; // template // using array_t = struct array; // int array_init(array_t* array); template int array_init(array_t* array); // Constructor template int array_uninit(array_t* array); // Destructor template int array_append(array_t* array, const DataType& value); #include #include #define INITIAL_CAPACITY 10 #define INCREASE_FACTOR 10 /** * @brief (private subroutine) * * @param array * @return int */ template int increase_capacity(array_t* array); template int array_init(array_t* array) { assert(array); int error = EXIT_SUCCESS; array->count = 0; array->capacity = INITIAL_CAPACITY; array->elements = (DataType*) calloc(INITIAL_CAPACITY, sizeof(DataType)); if (array->elements == NULL) { array->capacity = 0; error = EXIT_FAILURE; } return error; } template int array_uninit(array_t* array) { assert(array); free(array->elements); return EXIT_SUCCESS; } template int array_append(array_t* array, const DataType& value) { assert(array); int error = EXIT_SUCCESS; if (array->count == array->capacity) { error = increase_capacity(array); } if (error == EXIT_SUCCESS) { array->elements[array->count++] = value; } return error; } template int increase_capacity(array_t* array) { assert(array); int error = EXIT_SUCCESS; size_t new_capacity = INCREASE_FACTOR * array->capacity; DataType* new_elements = (DataType*) calloc(new_capacity, sizeof(DataType)); if (new_elements) { for (size_t index = 0; index < array->count; ++index) { new_elements[index] = array->elements[index]; } free(array->elements); array->capacity = new_capacity; array->elements = new_elements; } else { error = EXIT_FAILURE; } return error; } #endif // ARRAY_H