creacion de vector y su push back

This commit is contained in:
2025-09-19 02:18:34 -06:00
parent 016ef0dfec
commit 83d192d180
3 changed files with 58 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
#ifndef VECTOR_H
#define VECTOR_H
#include <stdlib.h>
typedef struct {
void* data; // Puntero a buffer genérico
size_t size; // Cantidad de elementos actualmente en el vector
size_t capacity; // Capacidad total del vector
size_t element_size; // Tamaño de cada elemento
} Vector;
void vector_init(Vector* v, size_t element_size, size_t initial_capacity);
void vector_push_back(Vector* v, const void* element);
void vector_pop_back(Vector* v);
void *vector_get(Vector* v, size_t index);
size_t vector_size(Vector* v);
size_t vector_capacity(Vector* v);
void vector_free(Vector* v);
#endif

View File

@@ -11,6 +11,7 @@
#endif // Terminamos la definición
// Contenedores
#include "containers/vector.h" // Arreglo dinámico
// Algoritmos

36
src/containers/vector.c Normal file
View File

@@ -0,0 +1,36 @@
#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++;
}