From 1765a0a22284de17262f4bf71d6f7088e87cc807 Mon Sep 17 00:00:00 2001 From: xolatile Date: Wed, 23 Aug 2023 19:32:40 -0400 Subject: [PATCH] Update... (: --- source/vector.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/source/vector.c b/source/vector.c index 332f8ab..bfcc9ee 100644 --- a/source/vector.c +++ b/source/vector.c @@ -14,6 +14,10 @@ typedef struct { char * c; } example_t; +extern void vector_init(vector_t * vector, + size_t element_size, + size_t element_count); + extern void vector_push(vector_t * vector, void * data); @@ -22,11 +26,34 @@ extern void vector_pop(vector_t * vector); extern void * vector_get(vector_t * vector, size_t element); +extern void vector_set(vector_t * vector, + void * data, + size_t element); + extern void vector_free(vector_t * vector); extern void example_print(example_t * example); -// Add only 1 new element to vector. +void vector_init(vector_t * vector, + size_t element_size, + size_t element_count) { + vector->data = NULL; + vector->element_size = element_size; + vector->element_count = element_count; + + vector->data = malloc(vector->element_size * vector->element_count); + + if ((! vector->data) && (vector->element_count)) { + // Handle or output error somehow? + puts("vector_init"); + exit(EXIT_FAILURE); + } + + memset(vector->data, + 0, + vector->element_size * vector->element_count); +} + void vector_push(vector_t * vector, void * data) { ++vector->element_count; @@ -34,7 +61,7 @@ void vector_push(vector_t * vector, vector->data = realloc(vector->data, vector->element_size * vector->element_count); - if (vector->data == NULL) { + if (! vector->data) { // Handle or output error somehow? puts("vector_push"); exit(EXIT_FAILURE); @@ -60,6 +87,20 @@ void * vector_get(vector_t * vector, return &vector->data[vector->element_size * element]; } +void vector_set(vector_t * vector, + void * data, + size_t element) { + if (element >= vector->element_count) { + // Handle or output error somehow? + puts("vector_set"); + exit(EXIT_FAILURE); + } + + memcpy(&vector->data[vector->element_size * element], + data, + vector->element_size); +} + void vector_free(vector_t * vector) { free(vector->data); } @@ -77,13 +118,11 @@ int main(void) { y = { 2, -2, "B" }, z = { 3, -3, "C" }; - vector.data = NULL; // Important to NULL it. - vector.element_size = sizeof(example_t); // Important to type it. - vector.element_count = 0UL; // Important to 0 it. + vector_init(&vector, sizeof(example_t), 10); - vector_push(&vector, &x); - vector_push(&vector, &y); - vector_push(&vector, &z); + vector_set(&vector, &x, 0); + vector_set(&vector, &y, 1); + vector_set(&vector, &z, 2); example_print(vector_get(&vector, 0)); example_print(vector_get(&vector, 1));