From ce536fcd435dac77ff6785b8b72eb6df4307f7ed Mon Sep 17 00:00:00 2001 From: "iliya.saroukha" <iliya.saroukha@hes-so.ch> Date: Mon, 28 Aug 2023 23:40:26 +0200 Subject: [PATCH] fix: vec_pop returns the value to the user instead of simply removing it --- struct/vec.c | 21 +++++++++++++++------ struct/vec.h | 2 +- vec_test.c | 5 ++++- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/struct/vec.c b/struct/vec.c index 18a58c8..c791665 100644 --- a/struct/vec.c +++ b/struct/vec.c @@ -192,15 +192,23 @@ bool is_in_vec(vec_t *vec, int64_t data) { } /** - * @brief Function that removes the last element in a vector + * @brief Function that removes the last element in the vector and returns it + * to the user * - * @param vec Vector from which to pop the value + * @param vec Vector from which the value will be removed + * @return Last element in the vector */ -void vec_pop(vec_t *vec) { +int64_t vec_pop(vec_t *vec) { - err_init(vec); + if (vec == NULL) { + fprintf(stderr, "Vector not initialised\n"); + return -1; + } - err_len_zero(vec); + if (vec->len == 0) { + fprintf(stderr, "Length of the vector is 0!\n"); + return -1; + } // needs resizing // should be extracted into separate function if (vec->len <= vec->capacity / 2) { @@ -212,6 +220,7 @@ void vec_pop(vec_t *vec) { } vec->len--; + return vec->data[vec->len]; } /** @@ -292,6 +301,6 @@ void vec_destroy(vec_t **vec) { free((*vec)->data); free((*vec)); - (*vec) = NULL; + *vec = NULL; } } diff --git a/struct/vec.h b/struct/vec.h index 99a00cc..856226f 100644 --- a/struct/vec.h +++ b/struct/vec.h @@ -20,7 +20,7 @@ extern bool is_in_vec(vec_t *vec, int64_t data); extern void vec_remove(vec_t *vec, size_t idx); -extern void vec_pop(vec_t *vec); +extern int64_t vec_pop(vec_t *vec); extern void vec_print(vec_t *vec); diff --git a/vec_test.c b/vec_test.c index 56e5961..a785ff1 100644 --- a/vec_test.c +++ b/vec_test.c @@ -56,6 +56,7 @@ int main(int argc, char **argv) { } int64_t to_push; + int64_t item_poped; size_t idx_to_drop; size_t idx_to_insert; @@ -79,7 +80,9 @@ int main(int argc, char **argv) { vec_remove(new_vec, idx_to_drop); break; case 3: - vec_pop(new_vec); + item_poped = vec_pop(new_vec); + fprintf(stdout, "Last value in the vector: %ld was removed\n", + item_poped); break; case 4: vec_print(new_vec); -- GitLab