number of mines not accurate

I'm developing a simple minesweeper using 2d arrays in c++. However I am stuck at
a point where the program seems to count the mines correctly for the most part except the boundaries (mainly first and last columns. I'll really appreciate if you keep it simple because i'm just a beginner and dont want to make thing complex for myself.

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
 int cout_mines(int (*c)[10])
{
	int mines=0;
	for(int X=0; X<10; X++)
	 for(int Y=0; Y<10; Y++){
      if (c[X][Y] != 9) 
	  {
		  if(c[X+1][Y]==9)
			  mines++;
		  if (c[X-1][Y]==9)
			  mines++;
		  if(c[X][Y+1]==9)
			  mines++;
		  if(c[X][Y-1]==9)
			  mines++;
		  if(c[X-1][Y-1]==9)
			  mines++;
		  if(c[X+1][Y+1]==9)
			  mines++;
		  if(c[X-1][Y+1]==9)
			  mines++;
		  if(c[X+1][Y-1]==9)
			  mines++;
		  c[X][Y]=mines;
	  }
	  mines=0;
	 }
	 char a=97;
	 cout<<endl<<endl<<" ";
	for(int k=0;k<10; k++)
		cout<<" "<<a++;
	for(int i=0; i<10; i++)
	{	
		cout<<endl;
		cout<<i<<" ";
		for(int j=0; j<10; j++)
			cout<<c[i][j]<<" ";
	}
	

return (*c)[10];
}
Last edited on
Before you access a neighbor tile you need to check that it exist.
and how should I do it?
How you do it is up to you but if you want minimum changes to your code you could just add a check inside each if statement, like this:
1
2
3
4
...
if (X > 0 && c[X-1][Y] == 9)
	mines++;
...


Note that the check should be before accessing the array element to avoid out-of-bounds access.

Talking about out-of-bounds, why are you returning (*c)[10] from the function? *c is the same as c[0], so you are accessing c[0][10] which seems to be out of bounds.
I got it Thanks a bunch
Topic archived. No new replies allowed.