I implemented a two-dimensional array in C and would like to know if the implementation is sound in terms of
Memory management
Potential bugs and other side effects that I missed
Code style (readability, naming conventions, etc...)
Clean code
Efficiency
The code compiles and runs without any error:
gcc -O -Wall main.c
``
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct Array {
double **data;
size_t rows;
size_t cols;
};
struct Array *NewArray(const size_t rows, const size_t cols){
if (rows <= 0 || cols <= 0){
return NULL;
}
struct Array *array = (struct Array *)malloc(sizeof(struct Array *));
array->rows = rows;
array->cols = cols;
array->data = (double **) malloc(rows * sizeof(double *));
for (size_t i = 0; i < rows; ++i) {
array->data[i] = (double *) malloc(cols * sizeof(double));
}
return array;
}
int FreeArray(struct Array *array){
if (array != NULL) {
return -1;
}
assert (array->data);
for (size_t i = 0; i < array->rows; ++i) {
free(array->data[i]);
}
free(array->data);
free(array);
return 0;
}
void PrintArray(const struct Array *array) {
for (int i=0; i<array->rows; ++i) {
for (int j=0; j<array->cols; ++j) {
printf("%.2lf ", array->data[i][j]);
}
printf("\n");
}
return;
}
int main(){
size_t rows = 2;
size_t cols = 4;
struct Array *M = NewArray(2, 4);
PrintArray(M);
FreeArray(M);
}