I want to create a function in C that allocates a dynamic matrix; the idea is to allocate an array whose elements are pointers to arrays; if I want to do that in a function, what is the correct code?
this
f(***matrix)
or this
f(**matrix)?
I would say the first one, but I'm not sure. thank you!
You probably want something like
double **
allocate_array(size_t rows, size_t cols)
{
double **array = malloc(cols * sizeof(*array));
if (array == NULL) return NULL;
for (size_t i = 0; i < cols; i++) {
array[i] = malloc(rows * sizeof(*array[i]));
for (size_t j = 0; j < rows; j++) array[i] = 0.0;
if (array[i] == NULL) {
while (i != 0) free(array[--i]);
free(array);
return NULL;
}
}
return array;
}