Question: I am very new to C and would just like to know the proper way to use malloc for the following structure:

```
struct cell {
    struct player* owner;
    int letter;
};

struct board {
    struct cell** matrix;
    int width;
    int height;
};

```

This structure is inside a 'board' struct which has also been created using malloc. I hope that is enough information and I appreciate any explanation.

Answer: 
```
struct cell {
    struct player* owner;
    int letter;
};

struct board {
    struct cell** matrix;
    int width;
    int height;
};

//this would work, but memory allocation is slow.
void fillBoard(board *b){
    b->matrix = (struct cell**)malloc(b->width * sizeof(struct cell*));
    for (int i = 0; i < b->height; i++){
        b->matrix[i] = (struct cell*)malloc(sizeof(struct cell));
    }
}

//to limit that you could rewrite it to this.
struct cell {
    struct player* owner;
    int letter;
};

struct board {
    struct cell* matrix;
    int width;
    int height;
};

//this only allocates memory once, so it is faster and it avoids memory fragmentation.
void fillBoard(board *b){
    b->matrix = (struct cell*)malloc(b->width * b->height * sizeof(struct cell));
}

//to access a certain cell, you have to do this (x * width + y)
struct cell *getCell(board *b, int x, int y){
    return &b->matrix[x * b->width + y];
}

```

Edit: I don't usually program in C. I mostly use C++, so there could be some mistakes in it.
> 
> the proper way to use malloc
> 
> 
> 

* Use helper functions rather than make a single function too complex.
* An allocation function should have a matching free function.
* Check for allocation and other errors.
* Allocate to the size of the referenced object, not type.
* Casting the result of `malloc()` is not needed.

Example:

```
#include <stdlib.h>

struct cell* cell_allocate(int width); // TBD code for OP
void cell_free(struct cell*); // TBD code for OP

void board_free(struct board *bd) {
  if (bd) {
    if (bd->matrix) {
      for (int h = 0; h < bd->height; h++) {
        cell_free(bd->matrix[h]);
      }
      free(bd->matrix);
    }
    free(bd->matrix);
  }
}

// Allocate 1 board.    
// Return NULL on error
struct board* board_allocate(int width, int height) {
  if (width <= 0 || height <= 0) {
    return NULL;
  }

  // Allocate board
  struct board *bd = malloc(sizeof *bd, 1);
  if (bd == NULL) {
    return NULL;
  }

  // Allocate matrix row pointers
  bd->matrix = malloc(sizeof *(bd->matrix) * (unsigned) height);
  if (bd->matrix == NULL) {
    board_free(bd);
    return NULL;
  }
  bd->width = width;
  bd->height = height;

  // Allocate matrix rows
  for (int h = 0; h < height; h++) {
    bd->matrix[h] = cell_allocate(width);
    if (bd->matrix[h] == NULL) {
      bd->height = h - 1;
      board_free(bd);
      return NULL;
    }
  }
  return bd;
}

```