rand() Crashes.

Hello, I am currently trying to program tic tac toe and the console crashes once i use the rand() funktion and try to assign it to a variable.

This is the whole code.

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
   string a[3][3] = {

   {"O","O","O"},
   {"O","O","O"}, //Spielfeld
   {"O","O","O"}

   };

int r1; //Variablen
int r2;
int h;
int v;
bool win=false;
bool possible=false;
int pos[2];




srand(time(0)); //randomiser seed



   cout<<"Gib die Koordinaten deines Feldes ein.Das Spielfeld ist so aufgebaut:"<<endl;
   cout<<"  0 1 2"<<endl;
   cout<<"0:O A O"<<endl;
   cout<<"1:A O B"<<endl; //Erklärung
   cout<<"2:B O A"<<endl;



while(win==false){


cin>>h; //Eingabe
cin>>v;


//Abfrage ob die Eingabe möglich ist
if(h<3&&h>=0&&v<3&&v>=0){



pos[0]= h;
pos[1]= v;




if(a[pos[1]][pos[0]]=="O"){



a[pos[1]][pos[0]]="A";

//Randomiser Anfang
while(possible==false){


r1 = rand();
r2 = rand();


        if(a[r1][r2]=="O"){
        possible=true;
        }

}

possible=false;


a[r1][r2]="B";


//Randomiser Ende

   for(int x=0;x<3;x++){

    for(int y=0;y<3;y++){

            if(y==2){

        cout<<a[x][y]<<endl; //ausgabe

            }else{

        cout<<a[x][y];
            }
    }

    }

} else {

 cout<<"Diese Feld ist schon belegt."<<endl;
}

   } else {
   cout<<"ungueltige Position."<<endl;

   }
   }


}





Once it tries to execute this part it starts crashing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Randomiser Anfang
while(possible==false){


r1 = rand();
r2 = rand();


        if(a[r1][r2]=="O"){
        possible=true;
        }

}

possible=false;


a[r1][r2]="B";


//Randomiser Ende 



I am a beginner so this may be a dumb mistake I made but I cant seem to find it :/.
a is a 3-by-3 matrix, but you try to index it with r1 and r2, which are two integers that have been directly assigned the return value of rand(). rand() returns a value between between 0 and RAND_MAX. RAND_MAX is usually around 32768.
In short, the program is crashing because you're reading way outside the bounds of an array.
Last edited on
Seems like I forgot to change it to (rand() % 2).
Thanks for helping ^^
Topic archived. No new replies allowed.