Home > database >  C 2D algorithm code is reading the array wrong
C 2D algorithm code is reading the array wrong

Time:10-23

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.

  • row 0, item 0, expected outcome 0, actual outcome 2
  • row 3, item 2, expected outcome 6, actual outcome 0
  • row 1, item 0, expected outcome 3, actual outcome 6
  • row 5, item 1, expected outcome 5, actual outcome 0
  • row 8, item 2, expected outcome 6, actual outcome 13629648
  • row 7, item 2, expected outcome 6, actual outcome 0

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related