Home > Enterprise >  Fill a 2d array of pointers with pointers to structs in C
Fill a 2d array of pointers with pointers to structs in C

Time:01-19

I have a 2 dimensional array of pointers:

typedef struct Cell{
   Position p;
   unsigned int value;
} Cell;

typedef struct Position{
    unsigned int x;
    unsigned int y;
} Position;

int size = 4;
Cell ***cells = malloc(sizeof(Cell**) * size);
int i,j;
for(i = 0; i < size; i  ){
    cells[i] = malloc(sizeof(Cell*) * size);
    for(j = 0; j < size; j  ){
        cells[i][j] = malloc(sizeof(Cell));
    }
}

What I want to do now is fill this array with pointers to cells, and initialize these cells to contain the value 0 like this:

for(i = 0; i < size; i  ){
    for(j = 0; j < size; j  ){
        Position p = {i,j};
        Cell c = {p, 0};
        cells[i][j] = &c; //This doesn't work
    }
}

As you can already tell, writing the address of c into the pointer cells[i][j] is less than ideal, since every pointer now points to the same address. However I don't know how to fill this array with pointers pointing to individual addresses.

I tried something like this:

cells[i][j]->value = 0;

which of course also doesn't work. Can anyone give me a hint on how I can solve my problem?

CodePudding user response:

I'm not sure why you say cells[i][j]->value = 0; doesn't work, I believe it should.

This should work to set all the members.

Cell ***cells = malloc(sizeof(Cell**) * size);
for(i = 0; i < size; i  ){
    cells[i] = malloc(sizeof(Cell*) * size);
    for(j = 0; j < size; j  ){
        cells[i][j] = malloc(sizeof(Cell));
        cells[i][j]->p.x = i;
        cells[i][j]->p.y = j;
        cells[i][j]->value = 0;
    }
}
  •  Tags:  
  • Related