我对这段代码很不满意,编译好了。但是,在内存无法写入错误后,它会立即崩溃。
调试器说问题出在行* 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);
}
答案 0 :(得分: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
,请不要使用它,只需使用好的'数组':
grid_t grid[GRID_HEIGHT][GRID_WIDTH];