I am currently writing a function which uses a bi-dimensional array of pointers to a structure cell
. I'll have to update each cell
with data read in a file.
As I will need to access the various cells, I have to deal with dynamic allocation. But what is the best way to use it here, as I don't need access to the array itself ? Can I use:
cell *p_cell[height][width] = malloc(height*width*sizeof(cell*));
Or:
cell *p_cell[height][width];
and then later on (in a for loop, for instance) :
p_cell[i][j] = malloc(sizeof(cell*));
data_type (*array) [width] = malloc( sizeof(data_type[height][width]) );
Now you can access the data using arr[i][j]
P.S: 2-D array should should be allocated as a contiguous chunk of memory, to get the best read write performance.
**Edit : ** As pointed out by chux in comment section that array
is not a 2-D array, it's a pointer to 1-D array.
In order to make array
as 2-D array, you need to declare it like this.
data_type (*array) [height][width] = malloc( sizeof(data_type[height][width]) );
It seems like you want a 2D array of pointers, which can be declared as:
cell *p_cell[height][width];
To allocate each of these cell *
pointers in p_cell[i][j]
, you can do this:
for (size_t i = 0; i < height; i++) {
for (size_t j = 0; j < width; j++) {
p_cell[i][j] = malloc(sizeof(cell));
/* check malloc */
/* access using p_cell[i][j]->something */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With