繁体   English   中英

如何将 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;
};

该结构位于“板”结构内,该结构也使用 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++,所以可能会有一些错误。

malloc的正确使用方法

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

  • 分配 function 应具有匹配的免费 function。

  • 检查分配和其他错误。

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

  • 不需要转换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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM