malloc 2D阵列导致EXC_BAD_ACCESS

时间:2017-07-17 17:17:34

标签: c

在尝试为生命游戏初始化棋盘时,我收到错误:

EXC_BAD_ACCESS (code=1, address=0x200000000)

第9行(我在评论中标记了它)。我使用malloc为2D阵列分配内存,一块满是struct cell s的板。我在StackOverflow上找到的方法。难道我做错了什么?此外,在我运行第6行发生的程序之前有一个警告:

Incompatible pointer types initializing 'struct cell *const' with an expression of type 'struct cell **'; dereference with *

这可能与它有关吗?这是代码:

void init_board(int nrows, int ncols, struct cell ***board){

    //allocate memory for a 2D array
    *board = malloc(nrows * sizeof(*board) + nrows * ncols * sizeof(**board));

    //Now set the address of each row 
    struct cell * const firstrow = *board + nrows;
    for(int i = 0; i < nrows; i++)
    {
        *board[i] = firstrow + i * ncols; //EXC_BAD_ACCESS...
    }

    for(int i = 0; i < nrows; i++){ //fill the entire board with pieces
        for(int j = 0; j < ncols; j++){
            *board[j][i] = new_cell(i, j, 0);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

[]的排序高于precedence而非*

    // *board[i] = firstrow + i * ncols; //EXC_BAD_ACCESS...
    (*board)[i] = firstrow + i * ncols; //EXC_BAD_ACCESS...

交换索引订单

        // *board[j][i] = new_cell(i, j, 0);
        (*board)[i][j] = new_cell(i, j, 0);