From 1d1d9c62cbd37f097b80b61cb1ed844bebb5d6fc Mon Sep 17 00:00:00 2001 From: Sander Speetjens Date: Wed, 7 Aug 2024 01:28:50 +0200 Subject: [PATCH] add array_realloc --- src/safe_array.c | 19 +++++++++++++++++++ src/safe_array.h | 8 ++++++++ tests/safe_array.cpp | 17 ++++++++++++++++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/safe_array.c b/src/safe_array.c index 29e8367..720b97c 100644 --- a/src/safe_array.c +++ b/src/safe_array.c @@ -42,6 +42,25 @@ array_t array_move(array_t* initial, size_t move) }; } +array_t *array_realloc(array_t* arr, size_t rows) +{ + if (!arr) + { + fprintf(stderr, "%s: ptr dereferences to NULL\n", __func__); + return NULL; + } + + array_t *new_arr = realloc(arr, sizeof(array_t) + (arr->size * rows - 1)); + if (!new_arr) + { + fprintf(stderr, "%s: Failed to reallocate memory for array", __func__); + return NULL; + } + + new_arr->rows = rows; + return new_arr; +} + size_t array_get_rows(array_t *arr) { if (!arr) diff --git a/src/safe_array.h b/src/safe_array.h index 7c2f36a..a117ded 100644 --- a/src/safe_array.h +++ b/src/safe_array.h @@ -54,6 +54,14 @@ array_t *array_init(size_t size, size_t rows); */ array_t array_move(array_t* initial, size_t move); +/** + * @brief This function reallocates the safe array + * + * @param arr The pointer to the safe array struct + * @param rows The number of rows to reallocate + */ +array_t *array_realloc(array_t* arr, size_t rows); + /** * @brief This function gets the number of rows in the safe array * diff --git a/tests/safe_array.cpp b/tests/safe_array.cpp index 0434b11..28a10d2 100644 --- a/tests/safe_array.cpp +++ b/tests/safe_array.cpp @@ -35,10 +35,25 @@ TEST(array, array_move) EXPECT_EQ(ARRAY_GET(&y, 6, double), 8); EXPECT_EQ(ARRAY_GET(&y, 7, double), 9); EXPECT_EQ(ARRAY_GET(&y, 8, double), 10); - + array_free(x); } +TEST(array, array_realloc) +{ + array_t* x = array_init(sizeof(double), 2); + ARRAY_GET(x, 0, double) = 1; + ARRAY_GET(x, 1, double) = 2; + + array_t* y = array_realloc(x, 3); + EXPECT_EQ(array_get_rows(y), 3); + EXPECT_EQ(ARRAY_GET(y, 0, double), 1); + EXPECT_EQ(ARRAY_GET(y, 1, double), 2); + EXPECT_EQ(ARRAY_GET(y, 2, double), 0); + + array_free(y); +} + TEST(array, Get_Set_array) { array_t* x = array_init(sizeof(double), 2);