Home > Back-end >  How to index a heap allocated matrix in C?
How to index a heap allocated matrix in C?

Time:11-21

I am making a minesweeper program in C.

I have this as a global variable:

typedef struct box_t
{
  int box_type;
  int num_mines_bordering;
  int is_flagged;
} box_t;

// my global
box_t * gameboard = NULL;

Later in the application it is allocated in the heap based on the number of rows and columns:


gameboard = (box_t *)malloc((rows * cols) * sizeof(box_t));

All is well, however, they way I index it now seems incorrect and error-prone. I can't simply do gameboard[x][y] because I get compiler errors and what I have now seems incorrect:

#define GET_LOC(ROW, COL) gameboard[(ROW * sizeof(box_t))   (COL * sizeof(box_t)) * sizeof(box_t)]
// if you call this it would look like: box_t * loc = &GET_LOC(somerow, somecol);

Is there a better way to index it?

CodePudding user response:

The compiler knows the type and hence the size of each array entry, so the only special thing is the number of columns cols:

box_t *gameboard = malloc((rows * cols) * sizeof(*gameboard));
gameboard[row * cols   col] = ...;
  • Related