0

我对这段代码有疑问,它编译正常。但它在内存无法写入错误后立即崩溃。

调试器说问题出在 *grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT); ,我一定遗漏了一些明显的东西。

我正在尝试创建一个指向 2D 结构的指针。

#define GRID_WIDTH 12
#define GRID_HEIGHT 22

typedef struct
{
    int piece;
    int edge;
}grid_t;

grid_t*** grid;

*grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT);

for(int i = 0 ; i < GRID_HEIGHT ; i++)
{
    *grid[i] = (grid_t*)malloc(sizeof(grid_t)*GRID_WIDTH);
}
4

1 回答 1

4

您取消引用未分配的指针:

grid_t*** grid;
*grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT);

grid当你这样做时没有分配*grid,所以它是未定义的行为。

如果要动态分配二维结构体,首先需要grid_t*在第一级为指针( )分配足够的内存:

grid_t** grid;
grid = malloc(sizeof(*grid) * GRID_HEIGHT);

然后您可以使用循环分配每个元素:

for(int i = 0 ; i < GRID_HEIGHT ; i++)
{
    grid[i] = malloc(sizeof(**grid) * GRID_WIDTH);
    // ...then you can do grid[i]->piece = 42; etc..
}

现在,据我所知,您甚至可能不需要动态分配。如果您不需要malloc,请不要使用它,只需使用好的 ol' 数组即可:

grid_t grid[GRID_HEIGHT][GRID_WIDTH];
于 2012-12-23T20:52:21.250 回答