Micah Lehman
Micah Lehman

Reputation: 81

C++ 2D algorithm code is reading the array wrong

Like the title said, my code is reading a 2D array entirely wrong.

    const int WINNING_ROWS[8][3] = { (0, 1, 2),
                                     (3, 4, 5),
                                     (6, 7, 8),
                                     (0, 3, 6),
                                     (1, 4, 7),
                                     (2, 5, 8),
                                     (0, 4, 8),
                                     (2, 4, 6) };

Above is my 2D array of numbers. My program doesn't seem to be able to read it properly.

For example, if I were to ask for row 2, item 1, I would expect 7, it, however, instead gives me 6. Here is a list of rows and item requests I have done to try and figure out what has gone wrong here.

for reference, here is the code I have been using to call the items from the array

cout << WINNING_ROWS[7][2] << endl;

Edit 1: ignore the item in bold, that was a mistake on my part when testing my code.

Edit 2: my question has been answered.

Upvotes: 0

Views: 58

Answers (2)

JDługosz
JDługosz

Reputation: 5652

const int WINNING_ROWS[8][3] = { (0, 1, 2),
                                     (3, 4, 5),
                                     (6, 7, 8),
                                     (0, 3, 6),
                                     (1, 4, 7),
                                     (2, 5, 8),
                                     (0, 4, 8),
                                     (2, 4, 6) };

That doesn't mean what you think it does. The (0,1,2) is not a row of three elements, but a single integer computed using the comma operator. 0,1,2 evaluates to 2.

You need to use the proper {...} braces instead of parenthesis, or leave them out completely.


Suggest also you change const to constexpr.

Upvotes: 4

nwatx
nwatx

Reputation: 118

WINNING_ROWS[8][2] is out of the array bounds, which means it will cause undefined behavior. If you want to get the last element, you should try cout << WINNING_ROWS[7][2] << endl; since they are 0-indexed.

Upvotes: 1

Related Questions