I've found an interesting way to allocate matrices in C which allows the use of [i][j]
without initializing as double matrix_a[nrows][ncols]
. The allocation is
double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));
But I can't find how to properly free this type of allocation. Would it be as simple as free(matrix_a)
?
That is correct. You may only pass to free
what was returned from malloc
and family. So since you did one malloc
, you do one free
.
Also, there is no need to cast the return value of malloc:
double (*matrix_a)[ncols] = malloc(sizeof(double) * (nrows) * (ncols));