我正在创建一个以2d数组为棋盘的游戏。最初,我试图在一个函数中将板动态分配给结构,但我想我会创建板,然后将这个新创建的板分配给结构中的双点。
这是我对结构体的声明。当我运行create board函数时,一切都正常,但当我打印到它时,出现了seg错误,所以我会认为我没有分配足够的空间,我的指针出现了问题。
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: %dn", num_rows);
printf("Create Board Cols: %dn", num_cols);
printf("Create Board Hidden Tile: %cn", 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;
}
更新
我相信我们的分割错误来自于我们的印刷板功能,我们试图用页眉打印印刷板。我成功地将这个确切的代码用于另一个函数,所以我想也许我访问我的板错了?
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("%dn", num_row_val);
printf("%dn", num_col_val);
printf("%dn", 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");
}
将struct Game_State
传递给函数时,传递的是变量的副本。更具体地说,create_board()
内部的game
变量的.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;