将动态分配的2D数组分配给结构中的双指针时出现段错误

时间:2016-06-04 02:11:15

标签: c pointers memory-management struct segmentation-fault

我正在创建一个以2D阵列作为棋盘的游戏。最初,我尝试在一个函数中动态地将板分配给结构,但是我想创建板,然后将这个新创建的板分配给结构中的双点。

这是我对结构的声明。当我运行我的创建板功能时,一切都工作正常,但是当我打印到它时会出现一个段错误,所以我假设我没有分配足够的空间而且我的指针存在问题。

typedef struct Game_State{
    int num_rows;
    int num_cols;
    int num_mines;
    char** board;
    char MINE;
    char hidden_tile;
    char marked_tile;
    char flagged_tile;
    char revealed_tile;
}game;

这是我用来创建动态分配板的代码,具体取决于行和列的命令行参数,但是当我打印板时,存在分段错误!

void create_board(struct Game_State game){
    //intitialization
    int i;
    int j;
    int num_rows = game.num_rows;
    int num_cols = game.num_cols;
    char  hidden_tile = game.hidden_tile;
    char** board; 
    printf("Create Board Rows: %d\n", num_rows);
    printf("Create Board Cols: %d\n", num_cols);
    printf("Create Board Hidden Tile: %c\n", hidden_tile);
    //dynamically allocates space for the board (2x2)
    board =(char**) malloc(num_rows *sizeof(char*));
    for(i = 0; i < num_rows; ++i){//for each row
        board[i] = (char*) malloc(num_cols * sizeof(char));
        for(j = 0; j < num_cols; ++j){
            board[i][j] = hidden_tile;
        }
    }
    game.board=board;
}

更新

我认为我们的分段错误来自我们的printboard功能,我们尝试使用标题打印主板。我使用这个确切的代码成功的另一个函数,所以我想我可能会错误地访问我的电路板?

void print_board(struct Game_State game){//defines print board function
    //intitializations
    int i = 0;
    int j = 0;
    int k = 0;
    int num_row_val = game.num_rows;
    int l = num_row_val;
    int num_col_val = game.num_cols;
    char** board =game.board

    printf("%d\n", num_row_val);
    printf("%d\n", num_col_val);
    printf("%d\n", l);

    while(l > 0){
        for(i = 0; i < num_row_val; ++i){
            printf("%d " , (l - 1));//prints row headers
            for(j = 0; j < num_col_val; ++j){//prints board
                printf("%c ",game.board[i][j]);
            }
            printf("\n");
            --l;
        }
    }
    for(k = 0; k < num_col_val; ++k){//prints column header
        printf(" %d" , k);
    }
    printf("\n");
}

1 个答案:

答案 0 :(得分:0)

当您将struct Game_State传递给某个函数时,您将传递该变量的副本。更具体地说,.boardgame变量的create_board()成员是传递给函数的变量的.board成员的副本。

因此,当您从create_board()函数返回时,game变量不再存在,并且您对分配的内存的唯一指针将无可挽回地丢失。 传递给函数的变量的.board成员仍然未初始化,毫不奇怪,您的程序在print_board()内崩溃。

每当您需要修改函数内的Game_State结构时,您需要将指针传递给 struct Game_State

void create_board (struct Game_State *game) {  /* Pointer to Game_State */
  ...
}

int main (void) {
    struct Game_State g;

    create_board (&g);  /* Address of g. */
    ...
}

您还必须以不同方式访问create_board()内的结构成员。这些行:

int num_rows = game.num_rows;
int num_cols = game.num_cols;
char  hidden_tile = game.hidden_tile;
...
game.board=board;

应更改为:

int num_rows = game->num_rows;
int num_cols = game->num_cols;
char  hidden_tile = game->hidden_tile;
...
game->board=board;

这是:

的简写
int num_rows = (*game).num_rows;
int num_cols = (*game).num_cols;
char  hidden_tile = (*game).hidden_tile;
...
(*game).board=board;