Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to index a heap allocated matrix in C?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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?

>Solution :

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] = ...;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading