I have the following typedef:
typedef struct cell_t {
int x; // x coord of this cell
int y; // y coord of this cell
int neighbour_count; // Size of the following array
struct cell_t **neighbours; // array of pointers to neighbours
} cell_t;
and some code to initialize this type (neighbour_count and neighbours are to be set later)
cell_t *create_cell(int x, int y){
cell_t *cell = malloc(sizeof(cell_t));
cell->x = x;
cell->y = y;
return cell;
}
I have myfun to initialize the neighbours and neighbour_count variables for a matrix of cell_t, which it reads from some external source.
int myfun(cell_t ***cells, int width, int height){
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// Read data from source, including the long `list_size`
cells[x][y]->neighbour_count = (int) list_size; // This segfaults
}
}
}
So in my main, I have the following:
int width = 3, height = 3;
cell_t *cells[width][height];
for (int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
cells[x][y] = create_cell(x,y);
}
}
myfun(cells, width, height);
When setting the neighbour count, it segfaults (as marked in the third block of code).
What I think I'm doing is that in my main I initialize an empty matrix of pointers to cell objects, and then loop through width and height, creating cells, and storing the pointers to them in the matrix. Then in myfun, I'm simply accessing a the variable neighbour_count of these cells and setting it. But apparently I'm mistaken, as it segfaults (not always on the first loop though, but generally quite quickly).
I'm thinking perhaps I did something wrong such that the matrix cells does not actually contain pointers to cell_t structs. But I can't see what I'm doing wrong.
I am getting a warning that "passing argument 1 of ‘myfun’ from incompatible pointer type", and that it should instead be of type cell_t * (*)[(sizetype)(height)]; perhaps that helps? I would expect there not to be a problem, as struct_t *** should be good for a 2d array of pointers, no?