2D Arrays in a Function

Hello, I am trying to create an AI Player for my Tic-Tac-Toe game, yet when I try to make the AI change to a random co-ordinates, it doesn't change the variable in the array, any suggestions? (Apologies if it is something obvious, 2D arrays are the bane of my life.)

1
2
3
4
5
6
7
8
9
10
11
  void AI(char board[][3])
{
int AI_choice = rand() % 10;
board[3][3] = AI_choice;


cout << "AI has gone for:" << AI_choice << endl;


}
2D arrays are just like 1D arrays. Except instead of being an array of ints.... it's an array of other arrays.

Take a look at your array defined here:

void AI(char board[][3])

Now... as with 1D arrays, if you have.. say.. int foo[5];, this means you have 5 individual elements in the array: [0], [1], [2], [3], and [4]. Anything above [4] is out of bounds... so if you try to do foo[5] = whatever; that is out of bounds and is very badtm.

Your 'board' array is the same thing. You have a 3x3 array, which means the minimum element is board[0][0], and the maximum element is board[2][2]. Anything above [2][2] is out of bounds.

Now look what you are doing on line 4:

 
board[3][3] = AI_choice; // <- DISASTER!  [3][3] is out of bounds! 
In addition to what Disch has pointed out you have another error at Line 3. Think of the modulus operator as hackish a way to set an upper limit for "rand()". In a board that has only nine squares, you're allowing the tenth position to be a possible value (arrays in C\C++ are zero indexed) this should be:

 
int AI_choice = rand() % 9;


You would use '9' so that any value returned by "rand()" that is a multiple of 9 would become 0 when modulated giving you a range of 0 - 8.
Alright, thanks for the help, guys! I'll update my program now. =)
Topic archived. No new replies allowed.