Minesweeper multi-dimensional array problem.

I am trying to create a minesweeper game and I am running into a problem setting up and populating the board. My intention is to create a 9x9 array and use a pair of random numbers between 1 and 9 to serve as locations for the mines and assigning a value of 10 to that location on the array and incrementing the surrounding squares by 1. Checking to make sure that the target spot in the array is already not greater than 10. This way once I get further on any value greater than 10 is a mine and and value 8 or lower is the number of adjacent mines.

When I run this code I am getting a 9x9 gird. The first 8 rows are all 0s. and the 9th row is random numbers none over 10. I do not see the problem. If any of you will direct me to where to look It would be appreciated.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Minesweeper
// Just like the classic only not as good.

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
	int gameboard[9][9];
	const int MINES = 10;

	// set default value of each square to zero
	for (int x = 0; x < 9; x++)
	{
		for (int y = 0; y < 9; y++)
		{
			gameboard[x][y] = 0;
		}
	}

	// Populate mines onto the board.  Mines are denoted by having a value higher than 10.  
	//Check to make sure same square is not selected twice.  Increment surrounding squares by 1.

	srand(static_cast<unsigned int>(time(0))); 

	int temp_x = 0;
	int temp_y = 0;

	for (int x = 0; x < MINES; x++)
	{
		do
		{
			temp_x = (rand() % 9) + 1;
			temp_y = (rand() % 9) + 1;
		} while (gameboard[temp_x][temp_y] < 10);

		gameboard[temp_x][temp_y] += 10;

		gameboard[(temp_x - 1)][(temp_y + 1)]++ ;
		gameboard[(temp_x)][(temp_y + 1)]++ ;
		gameboard[(temp_x + 1)][(temp_y + 1)]++ ;
		gameboard[(temp_x + 1)][(temp_y)]++ ;
		gameboard[(temp_x + 1)][(temp_y - 1)]++ ;
		gameboard[(temp_x)][(temp_y - 1)]++ ;
		gameboard[(temp_x - 1)][(temp_y - 1)]++ ;
		gameboard[(temp_x - 1)][(temp_y)]++ ;

	}

	// Just for display to make sure it is working as intended.

	for (int x = 0; x < 9; x++)
	{
		for (int y = 0; y < 9; y++)
		{
			cout << gameboard[x][y] << "  ";
		}
		cout << endl;
	}
	
	cin.ignore();
	cin.get();
	return 0;
}
Since the index starts with 0 only indexes from 0 upto 8 (this are the nine elements of the array) are allowed. All indexes starting with 9 are out of bounds and accessing them leads to an undefined behavior including a crash.

So if you want 10 elements you need to increase the array or you need to check explicitely the out of bounds condition.
Topic archived. No new replies allowed.