mc2017 -4 years ago 51
C Question

Recursive Function in Minesweeper

I'm currently working on coding the game of minesweeper for a school project, but I'm stuck on the part where we reveal the mine that the user wants and if it's a 0, reveal all the mines around it, and so on. I made my game board 2 rows and columns larger than what the actual user-specified game board size should be so that I have a border around it to count the number of mines around edge cases. (num_rows and num_cols are the dimensions that the board actually should be)

``````x x x x x x x   Quick illustration of what my board looks like.
x . . . . . x   '.' in this picture represent tiles of the actual game
x . . . . . x   board while 'x' is the border around it
x . . . . . x
x . . . . . x
x x x x x x x
``````

The code that I posted below always results in segmentation error. I think that it's a problem with when I run into the border. Anyone have any suggestions? Sorry if the code is really bad/hard to read. I'm a beginner to C and programming in general. Thanks in advance!

``````typedef struct Tile_struct {  //board struct definitions
int visibility;
int num_mines_around;
} Tile;

typedef struct Board_struct {
int num_rows;
int num_cols;
int num_mines;
Tile** the_board;
} Board;

//This is how I allocated memory for the board
void CreateBoard(char** argv, Board* board) {

int row, col;

board->num_rows = atoi(argv[1]);
board->num_cols = atoi(argv[2]);
board->num_mines = atoi(argv[3]);

board->the_board = (Tile**)malloc(board->num_rows * sizeof(Tile*));

for (row = 0; row < (board->num_rows) + 2; row++) {

board->the_board[row] = (Tile*)malloc(board->num_cols *
sizeof(Tile));

for (col = 0; col < (board->num_cols) + 2; col++) {

board->the_board[row][col].visibility = 0;  //hide all tiles
}
}
}

void RevealTiles(Board* board, int row, int col) {

int i, j;

if (row <= 0 || row >= board->num_rows + 1 || col <= 0 || col >=
board->num_cols + 1) {
return;
}
else if (board->the_board[row][col].num_mines_around != 0) {
board->the_board[row][col].visibility = 4;  //reveal that tile
}
else {
board->the_board[row][col].visibility = 4;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i == row && j == col) {
continue;
}
RevealTiles(board, i, j);
}
}
}
}
``````

``````(Tile*)malloc(board->num_cols * sizeof(Tile));