我正在用 C 编写扫雷游戏。我希望能够玩具有不同大小和数量的地雷的不同雷区的游戏我创建了这样的结构来描述我的数据:
typedef struct t_Place Place;
struct t_Place{
unsigned numberOfMinesNear;
int mine;
int state;
};
typedef struct t_Minefield Minefield;
struct t_Minefield{
int xSize;
int ySize;
unsigned minesNumber;
Place **places;
};
所以,现在我正在尝试初始化我的雷区。我执行以下操作:
void makeGame(Minefield *minefield, unsigned x, unsigned y, unsigned mines){
int i, j;
minefield->places = malloc(x * y * sizeof(Place));
for(i = 0; i < x; i++)
for(j = 0; j < y; j++){
minefield->places[i][j].mine = EMPTY;
minefield->places[i][j].state = HIDDEN;
minefield->places[i][j].numberOfMinesNear = 0;
}
minefield->xSize = x;
minefield->ySize = y;
unsigned minesToPlace = mines;
srand(time(NULL));
while(minesToPlace > 0){
i = rand() % x;
j = rand() % y;
if(minefield->places[i][j].mine)
continue;
minefield->places[i][j].mine = MINE;
minesToPlace--;
}
minefield->minesNumber = mines;
// here will be call of play(minefield) function to start the game
}
int main(){
Minefield *gameField = (Minefield *) malloc(sizeof(Minefield));
makeGame(gameField, DEFAULT_X, DEFAULT_Y, DEFAULT_MINES);
// DEFAULT_X = DEFAULT_Y = DEFAULT_MINES = 10
free(gameField);
return 0;
}
我在 makeGame 函数的第一行代码中遇到了段错误。我做错了什么?我想动态地而不是静态地为我的雷区分配内存。