2

Learning about arrays, pointers, and references. Attempting to pass a chessboard 8x8 size array as a function parameter to print the array.

Is it not possible to use a range-based loop, or should I use a basic for-loop? Or am I simply setting the first value incorrectly? Without templates.

The first value [0][0] should be a 1, not multiple 1s.

#include <iostream>
void print(int (&board)[8][8])
{
  for (auto &x : board)
    {
      for (auto &y : board)
        {
          std::cout << board[*x][*y] << '\t';
        }
      std::cout << std::endl;
    }
}

int main (int argc, const char **argv)
{
  // Attempting to initialize all 8x8 to 0
  int board[8][8] = { { 0 } }; 
  // Set position [0][0] to value 1;
  board[0][0] = { 1 };
  // Print chessboard
  print(board);
}

Output

      /*          Output (Incorrect)
       *    0   0   0   0   0   0   0   0   
            0   1   1   1   1   1   1   1   
            0   1   1   1   1   1   1   1   
            0   1   1   1   1   1   1   1   
            0   1   1   1   1   1   1   1   
            0   1   1   1   1   1   1   1   
            0   1   1   1   1   1   1   1   
            0   1   1   1   1   1   1   1   
       *     
       */

Expected

      /*          Output (CORRECT)
       *    1   0   0   0   0   0   0   0   
            0   0   0   0   0   0   0   0
            0   0   0   0   0   0   0   0   
            0   0   0   0   0   0   0   0   
            0   0   0   0   0   0   0   0   
            0   0   0   0   0   0   0   0
            0   0   0   0   0   0   0   0   
            0   0   0   0   0   0   0   0   
       *     
       */

1 Answer 1

4

x and y are the element, not the index of the array. You could change the range-based for loop to

for (auto &row : board)
{
  for (auto element : row)
    {
      std::cout << element << '\t';
    }
  std::cout << std::endl;
}

LIVE

Sign up to request clarification or add additional context in comments.

1 Comment

The correct answer, thanks for the quick response. I have to wait for the time limit to accept this as the correct answer. But this worked, thank you! Will accept. Really appreciate you taking the time out to answer and point this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.