【发布时间】:2021-05-12 23:54:18
【问题描述】:
我有这两种结构:
typedef struct {
unsigned int rows;
unsigned int cols;
Cell ***cells;
} Board;
typedef struct {
unsigned int info;
unsigned char state;
unsigned int mines;
} Cell;
初始化板结构:
board = (Board*) malloc(sizeof(Board));
board->rows = 2;
board->cols = 2;
board->cells = NULL;
之后我调用这个函数:
int initCells(Board **board) {
Cell **cells = (Cell**) malloc((*board)->rows * sizeof(Cell*));
for (int i = 0; i < (*board)->rows; i++) {
cells[i] = (Cell*) malloc((*board)->cols * sizeof(Cell));
}
(*board)->cells = &cells;
(*board)->cells[0][0]->info = 7;
(*board)->cells[0][1]->info = 7;
(*board)->cells[1][0]->info = 7; // segmentation fault
return 0;
}
为什么我会出现第三个分段错误,将内存分配给三重指针的正确方法是什么?
【问题讨论】:
-
Cell ***cells有什么意义,是 3D 版的扫雷还是什么的? -
我怀疑你更喜欢
Cell (*cells)[MAX_COLS];然后board.cells = malloc( sizeof(Cell[rows][cols]) );...free(board.cells)。 -
函数中的
cells变量是单个指针而不是数组。所以在赋值中,&cells是一个指向单个指针的指针。当您执行(*board)->cells[x]时,您将其视为一个数组。您肯定希望板结构具有Cell **cells;,以便它是指向分配内存的指针,而不是指向分配内存的局部变量的地址。