Here are two ways to allocate your 2D array:
cell *(*p_cell)[height][width] = malloc(sizeof(*p_cell));
p_cell
is a pointer to a 2D array of pointers to cell
objects. Item at coordinates i
, j
is retrieved with:
cell *p = (*p_cell)[i][j];
It is probably easier to make p_cell
a pointer to an array of arrays:
cell *(*p_cell)[][width] = malloc(height * sizeof(*p_cell));
You would get the item at coordinates i
, j
with
cell *p = p_cell[i][j];
The above arrays are uninitialized, you would need to initialize them with pointers to existing cell
objects or pointers to allocated cell
objects.
If the 2D array is only used locally in your function and dimensions width
and height
are not too large, you can define the 2D array with local storage:
cell *p_cell[height][width];
As width
and height
are dynamic values, static initialization is not available. You must initialize this array with a nested loop, like the allocated ones.
The question is: Do you really need the element type to be a pointer to cell
?. It is only useful if you are going to make some of these pointers point to the same object or have a null value, or point to cell
objects referenced elsewhere. Otherwise, it would be much easier to use an array of cell
objects, either local to the function or allocated with malloc()
or calloc()
:
cell p_cell[][width] = calloc(sizeof(*p_cell), height);