Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bi-dimensional array of pointers [duplicate]

Tags:

arrays

c

pointers

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*));
like image 562
narfi Avatar asked Feb 06 '23 02:02

narfi


2 Answers

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]) );
like image 200
Shravan40 Avatar answered Feb 18 '23 08:02

Shravan40


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 */
    }
}
like image 31
RoadRunner Avatar answered Feb 18 '23 07:02

RoadRunner