在动态分配多维数组时,如何初始化struct对象的值?

时间:2016-12-06 01:56:49

标签: c multidimensional-array struct

我一直试图找出问题所在,我只是看不到它 它是一个扫雷网格,我正在尝试为一个指向struct Cell类型的对象的2D数组分配内存,并设置其值。
当我使用这个函数时,我得到一个单元网格,我可以从中询问它们的值,但这些都是NULL 我知道错误就在这里,因为我使用了一个为我分配的库,而我的代码也是如此。我现在必须自己编写分配。

struct Cell*** allocate_grid(int grid_width, int grid_height) {
    struct Cell*** grid = malloc(grid_width * sizeof(*grid));
    int column;
    for (column = 0; column < grid_width; column++) {
        grid[column] = malloc(grid_height * sizeof(**grid));
        int row;
        for (row = 0; row < grid_height; row++) {
            struct Cell cell = {COVERED, 0, false}; //state, neighbouring mines, is_mine
            grid[column][row] = &cell;
      }
    }
    return grid;
}

1 个答案:

答案 0 :(得分:1)

我必须使用malloc手动为单元本身分配内存。

struct Cell* alloc_cell(enum State state, int neighbouring_mines, bool is_mine) {
    struct Cell* cell = malloc(sizeof(cell));
    cell->state = state;
    cell->neighbouring_mines = neighbouring_mines;
    cell->is_mine = is_mine;
    return cell;
}

struct Cell*** allocate_grid(int grid_width, int grid_height) {
    struct Cell*** grid = malloc(grid_width * sizeof(*grid));
    int column;
    for (column = 0; column < grid_width; column++) {
        grid[column] = malloc(grid_height * sizeof(**grid));
        int row;
        for (row = 0; row < grid_height; row++) {
            grid[column][row] = alloc_cell(COVERED, 0, false);
      }
    }
    return grid;
}