Reputation: 6058
I made an array and set the values from 1 to 9 in the initializeBoard
function, but for some reason when I print the values they come out 0 to 8. Why is this happening? Shouldn't it print out 1 to 9 since those are the numbers I put in the array in initializeBoard
?
int main()
{
initializeBoard();
ticTacToeBoard();
}
void initializeBoard()
{
for (int i = 1; i < 9; i++)
ticTacBoard[i] = i;
cout << endl;
}
void ticTacToeBoard ()
{
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
cout << ticTacBoard[3 * y + x] << " ";
cout << endl;
}
}
Upvotes: 1
Views: 86
Reputation: 298056
Your i
starts at 0
, so your first value will be 0
. Since the inequality i < 9
breaks when i = 9
, i
is actually never 9
(the loop exits before your code is actually run).
Try using <=
instead of just <
to account for i = 9
:
for (int i = 1; i <= 9; i++)
{
ticTacBoard[i - 1] = i;
}
Other than that, arrays are indexed starting from 0
in C++ (and virtually every other language), so the first element is array[0]
, second is array[1]
, etc.
You'll have to subtract 1
from your array index.
Upvotes: -1
Reputation: 39224
The loop:
for (int i = 1; i < 9; i++)
{
ticTacBoard[i] = i;
}
will only do 1-8 since it will stop when i++ increases it to 9, so you're not initializing all 9 elements.
You should realistically do the same loop like this:
for (int i = 0; i < 9; i++)
{
ticTacBoard[i] = (i + 1);
}
Upvotes: 2
Reputation: 837946
You have an off-by-one error. Arrays use zero-based indexing in C++. Your code does not assign a value to the zeroth element of the array.
Try this instead:
for (int i = 0; i < 9; i++)
{
ticTacBoard[i] = i + 1;
}
Upvotes: 8
Reputation: 7333
Two suggestions:
ticTacBoard
before accessing it with []
? Make sure you give it enough memory for all of your slots! (I'm guessing you're doing tic tac toe, so you'll want 3x3 = 9 slots)for (i=0; i<9; i++)
Hope this helps!
Upvotes: 1
Reputation: 691
Problem lies in:
ticTacBoard[i] = i;
Should be:
ticTacBoard[i-1] = i;
Upvotes: 1