diff --git a/struct/vec.c b/struct/vec.c index 18a58c8213e1657af58ec163f0ebd5acab8cf83d..c791665e9af76f06a66c14fe10e3c2420d30f9cb 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 99a00cc82026e5f92e725de789ad664153e70e8e..856226f058a33b2c36d63a5e4f963047d2a2f92f 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 56e5961aa41204d0d25e6a6aa5874a3d16d9f2ce..a785ff1a08fe09386377968082014d079b47add4 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);