如何将 malloc 用于另一个使用 malloc 创建的结构中的结构数组

How do I use malloc for an array of structs inside another struct that has been created using malloc

我是 C 的新手,只想知道对以下结构使用 malloc 的正确方法:

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

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

此结构位于 'board' 结构内,该结构也是使用 malloc 创建的。我希望这是足够的信息,我很感激任何解释。

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];
}

编辑:我通常不使用 C 编程。我主要使用 C++,因此其中可能存在一些错误。

the proper way to use malloc

  • 使用辅助函数而不是让单个函数过于复杂。

  • 一个分配函数应该有一个匹配的自由函数。

  • 检查分配和其他错误。

  • 分配给引用对象的大小,而不是类型。

  • 不需要转换 malloc() 的结果。

示例:

#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;
}