Two-dimensional array of pointers

I am currently writing a function that uses a two-dimensional array of pointers to a structure cell. I will need to update each celldata read in the file. Since I will need to access different cells, I have to deal with dynamic allocation. But what is the best way to use it here, since 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 (in a for loop, for example):

p_cell[i][j] = malloc(sizeof(cell*));
+4
source share
3 answers

It seems you need a 2D array of pointers that can be declared as:

cell *p_cell[height][width];

cell * p_cell[i][j], :

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 */
    }
}
+2
data_type (*array) [width] = malloc( sizeof(data_type[height][width]) );

arr[i][j]

P.S: 2-D , .

** : ** chux , array 2-D , 1-D .

array 2-D , .

data_type (*array) [height][width] = malloc( sizeof(data_type[height][width]) );
+4

2D-:

cell *(*p_cell)[height][width] = malloc(sizeof(*p_cell));

p_cell - cell. i, j :

cell *p = (*p_cell)[i][j];

, p_cell :

cell *(*p_cell)[][width] = malloc(height * sizeof(*p_cell));

i, j

cell *p = p_cell[i][j];

, cell cell.

2D- , width height , 2D- :

 cell *p_cell[height][width];

width height , . , .

Question: Do you really need an element type as a pointer to cell? . This is only useful if you want some of these pointers to point to the same object or have a null value, or point to objects cellthat are referenced elsewhere. Otherwise, it would be much easier to use an array of objects cell, local or functional, or allocated with malloc()or calloc():

cell p_cell[][width] = calloc(sizeof(*p_cell), height);
+2
source

Source: https://habr.com/ru/post/1669515/


All Articles