Create array_move

This commit is contained in:
2024-08-07 01:11:24 +02:00
parent a3f6d2b304
commit e5bc729a25
3 changed files with 59 additions and 0 deletions

View File

@@ -35,6 +35,34 @@ array_t *array_init(size_t size, size_t rows)
return arr;
}
/**
* @brief This function creates a new array that uses the original array
*
* @param initial The pointer to the original safe array struct
* @param move The amount of rows to move
* @return array_t The new safe array struct that uses the original array
*/
array_t array_move(array_t* initial, size_t move)
{
if (initial->size <= move)
{
fprintf(stderr, "%s: initial->size <= move", __func__);
return (array_t){.rows = 0, .ptr = 0, .size = 0};
}
return (array_t) {
.size = initial->size,
.rows = initial->rows - move,
.ptr = initial->ptr + (move * initial->size)
};
}
/**
* @brief This function gets the number of rows in the safe array
*
* @param arr The pointer to the safe array struct
* @return size_t The number of rows
*/
size_t array_get_rows(array_t *arr)
{
if (!arr)

View File

@@ -38,6 +38,7 @@ typedef struct array_2d_s
// Array.c
array_t *array_init(size_t size, size_t rows);
array_t array_move(array_t* initial, size_t move);
size_t array_get_rows(array_t *arr);
void *array_get(array_t *arr, size_t index);
int array_set(array_t *arr, size_t index, void *element);

View File

@@ -9,6 +9,36 @@ TEST(array, array_init)
array_free(x);
}
TEST(array, array_move)
{
array_t* x = array_init(sizeof(double), 10);
ARRAY_GET(x, 0, double) = 1;
ARRAY_GET(x, 1, double) = 2;
ARRAY_GET(x, 2, double) = 3;
ARRAY_GET(x, 3, double) = 4;
ARRAY_GET(x, 4, double) = 5;
ARRAY_GET(x, 5, double) = 6;
ARRAY_GET(x, 6, double) = 7;
ARRAY_GET(x, 7, double) = 8;
ARRAY_GET(x, 8, double) = 9;
ARRAY_GET(x, 9, double) = 10;
array_t y = array_move(x, 1);
EXPECT_EQ(array_get_rows(&y), 9);
EXPECT_EQ(ARRAY_GET(&y, 0, double), 2);
EXPECT_EQ(ARRAY_GET(&y, 1, double), 3);
EXPECT_EQ(ARRAY_GET(&y, 2, double), 4);
EXPECT_EQ(ARRAY_GET(&y, 3, double), 5);
EXPECT_EQ(ARRAY_GET(&y, 4, double), 6);
EXPECT_EQ(ARRAY_GET(&y, 5, double), 7);
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, Get_Set_array)
{
array_t* x = array_init(sizeof(double), 2);