add array_realloc

This commit is contained in:
2024-08-07 01:28:50 +02:00
parent 04b2bbe89e
commit 1d1d9c62cb
3 changed files with 43 additions and 1 deletions

View File

@@ -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) size_t array_get_rows(array_t *arr)
{ {
if (!arr) if (!arr)

View File

@@ -54,6 +54,14 @@ array_t *array_init(size_t size, size_t rows);
*/ */
array_t array_move(array_t* initial, size_t move); 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 * @brief This function gets the number of rows in the safe array
* *

View File

@@ -35,10 +35,25 @@ TEST(array, array_move)
EXPECT_EQ(ARRAY_GET(&y, 6, double), 8); EXPECT_EQ(ARRAY_GET(&y, 6, double), 8);
EXPECT_EQ(ARRAY_GET(&y, 7, double), 9); EXPECT_EQ(ARRAY_GET(&y, 7, double), 9);
EXPECT_EQ(ARRAY_GET(&y, 8, double), 10); EXPECT_EQ(ARRAY_GET(&y, 8, double), 10);
array_free(x); 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) TEST(array, Get_Set_array)
{ {
array_t* x = array_init(sizeof(double), 2); array_t* x = array_init(sizeof(double), 2);