mardi 10 septembre 2019

Range based auto loop for multi-dimensional array as a function parameter

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   
       *     
       */

Aucun commentaire:

Enregistrer un commentaire