Memory optimize the 1d and 2d arrays

This commit is contained in:
2023-11-04 16:48:14 +01:00
parent 75b8cfe46b
commit d03ca99438
2 changed files with 8 additions and 24 deletions

View File

@@ -21,19 +21,12 @@
*/
array_t *array_init(size_t size, size_t rows)
{
array_t *arr = calloc(sizeof(array_t), 1);
array_t *arr = calloc(sizeof(array_t) + (size * rows), 1);
if (!arr)
{
fprintf(stderr, "%s: Failed to allocate memory for array", __func__);
return NULL;
}
arr->data = calloc(size, rows);
if (!arr->data)
{
fprintf(stderr, "%s: Failed to allocate memory for data", __func__);
free(arr);
return NULL;
}
arr->rows = rows;
arr->size = size;
@@ -103,7 +96,6 @@ void array_free(array_t *arr)
{
fprintf(stderr, "%s: ptr dereferences to NULL\n", __func__);
}
free(arr->data);
free(arr);
}
@@ -117,19 +109,12 @@ void array_free(array_t *arr)
*/
array_2d_t *array_2d_init(size_t size, size_t rows, size_t cols)
{
array_2d_t *arr = calloc(sizeof(array_2d_t), 1);
array_2d_t *arr = calloc(sizeof(array_2d_t) + (size * rows * cols), 1);
if (!arr)
{
fprintf(stderr, "%s: Failed to allocate memory for array", __func__);
return NULL;
}
arr->data = calloc(size, rows * cols);
if (!arr->data)
{
fprintf(stderr, "%s: Failed to allocate memory for data", __func__);
free(arr);
return NULL;
}
arr->rows = rows;
arr->cols = cols;
@@ -205,7 +190,6 @@ void array_2d_free(array_2d_t *x)
{
fprintf(stderr, "%s: ptr dereferences to NULL\n", __func__);
}
free(x->data);
free(x);
}

View File

@@ -25,33 +25,33 @@
typedef struct array_s
{
void *data;
size_t rows;
size_t size;
uint8_t data[1];
} array_t;
typedef struct array_2d_s
{
void *data;
size_t rows;
size_t cols;
size_t size;
uint8_t data[1];
} array_2d_t;
typedef struct array_c_s
{
void *real;
void *imaginary;
size_t rows;
size_t size;
void *real;
void *imaginary;
} array_c_s_t;
typedef struct array_c_p_s
{
void *magnitude;
void *phase;
size_t rows;
size_t size;
void *magnitude;
void *phase;
} array_c_p_t;
// Array.c