37 lines
1.1 KiB
C
37 lines
1.1 KiB
C
#include "pch.h"
|
|
#include "containers/vector.h"
|
|
#include <stdio.h>
|
|
|
|
void vector_init(Vector* v, size_t element_size, size_t initial_capacity) {
|
|
v->data = malloc(element_size * initial_capacity);
|
|
if (!v->data) {
|
|
// Manejo de error de asignación de memoria
|
|
v->size = 0;
|
|
v->capacity = 0;
|
|
v->element_size = 0;
|
|
return;
|
|
}
|
|
v->size = 0;
|
|
v->capacity = initial_capacity;
|
|
v->element_size = element_size;
|
|
}
|
|
|
|
void vector_push_back(Vector* v, const void* element) {
|
|
if (v->size == v->capacity) {
|
|
// Si está lleno, aumentamos la capacidad
|
|
size_t new_capacity = v->capacity == 0 ? 1 : v->capacity * 2;
|
|
void* new_data = realloc(v->data, v->element_size * new_capacity);
|
|
if (!new_data) {
|
|
// En caso de error de realloc, imprimimos un mensaje y salimos
|
|
fprintf(stderr, "Error: No se pudo asignar memoria en push_back, elemento no agregado\n");
|
|
return;
|
|
}
|
|
v->data = new_data;
|
|
v->capacity = new_capacity;
|
|
}
|
|
|
|
// Copiamos el nuevo elemento al final del vector
|
|
memcpy((char*)v->data + v->size * v->element_size, element, v->element_size);
|
|
v->size++;
|
|
}
|