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?
cells[i][j] = malloc(sizeof(Cell));That already sets the entry with a pointer to a struct. Later on you should just be using that pointer.*(cells[i][j]) = cwill copy thecstruct contents into the struct pointed to by the array entry.&cto the cells, because those pointers become invalid. You're also creating a memory leak, since you're overwriting the pointers that pointed to the memory created withmalloc().