Console crash

Hello i've got a problem.
i'am writing a game using a char raster that looks like:
1
2
3
4
5
6
7
8
    char raster[5][5] = 
    {
         {' ',' ',' ',' ',' '},
         {' ',' ',' ',' ',' '},
         {' ',' ',' ',' ',' '},
         {' ',' ',' ',' ',' '},
         {' ',' ',' ',' ',' '}
    }; 


I want a enemy to appear on a random place and make a random move.
I came up with the following:

1
2
3
o = random(1,4);
p = random(1,4);
raster[o][p] = en;


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
do {
         int ab = 1;
         int ac = 2;
         int ad = 3;
         int ae = 4;
         ran = random(1,4); 
         if(ran == ab)
         {
              raster[o][p] = ' ';
              o--;
              raster[o][p] = en;
         }
         else if(ran == ac)
         {
              raster[o][p] = ' ';
              o++;
              raster[o][p] = en;
         }
         else if(ran == ad)
         {
              raster[o][p] = ' ';
              p++;
              raster[o][p] = en;
         }
         else if(ran == ae)
         {
              raster[o][p] = ' ';
              p--;
              raster[o][p] = en;
         }
}while(4 < o || o < 0 || p < 0 || p > 4);


and this function:

1
2
3
4
5
int random(int min, int max)
{
  srand(time(0));
  return rand()%(max-min+1)+min;
}


but every time the enemy reaches the edge of the field the console crashes.
Can someone help me?
Last edited on
Accessing out of bounds is an error.
Don't do it.
Sorry but what do you mean with out of bounds?
Change this line: while(4 < o || o < 0 || p < 0 || p > 4) to while ( 4 < o && o < 0 && p < 0 && p > 4 )
Thanks a lot!
nm
Last edited on
Here is the array declaration:
char raster[5][5]

The valid range for the subscript (or index) is 0 to 4.
The very first element is raster[0][0]
and the last is char raster[4][4]

If you try (deliberately or accidentally) to update an element with an index bigger than 4 or smaller than 0, then the memory being accessed is not part of the array. That means it is out of bounds.

That is the cause (sooner or later, as it is unpredictable) of the program crash.
$ dict out-of-bounds
outside the delimited playing field.
Syn: off-limits.

Beyond the limits of the expected standard of taste or propriety


Look at your loop condition do /**/ while(4 < o || o < 0 || p < 0 || p > 4);
It breaks when the coordinate (o;p) is invalid.
However, you do access it raster[o][p] = en; before.
You may enter the loop with legal values of o and p, but you have a problem at lines 16 and 22. Assume that o or p has a value of 4. Those lines will increment o or p to 5., so now at lines 17 and 23, you're now trying to refer to raster[5][p] or raster[o][5]. Either of which is out of bounds. Subscripts start at 0. Therefore, the legal subscripts to raster are 0-4.
Thanks again
Topic archived. No new replies allowed.