Getter returning 2d array in C++
2d, arrays, c++, function, getter
Solution
You cannot pass arrays by value into and out of functions. But there's various options.
(1) Use a `std::array<type, size>`
#include <array>
typedef std::array<int, m_cols> row_type;
typedef std::array<row_type, m_rows> array_type;
array_type& getBoard() {return m_board;}
const array_type& getBoard() const {return m_board;}
private:
array_type m_board;
(2) Use the correct pointer type.
int *getBoard() {return m_board;}
const int *getBoard() const {return m_board;}
private:
int m_board[m_rows][m_cols];
An `int[][]` has no pointers involved. It isn't a pointer to an array of pointers to arrays of integers, it's an array of an array of integers.
//row 1 //row2
[[int][int][int][int]][[int][int][int][int]]
Which means one `int*` points to all of them. To get to a row offset, you'd do something like this:
int& array_offset(int* array, int numcols, int rowoffset, int coloffset)
{return array[numcols*rowoffset+coloffset];}
int& offset2_3 = array_offset(obj.getBoard(), obj.m_cols, 2, 3);
Problem
this is my first post on SO, even though i've spent some time already here. I've got here a problem with a function returning a 2d array. I have defined a private 2d int array property int board[6][7] in my Game class, but i don't know how to create a public getter for this property. These are relevant parts of my game.h: ``` #ifndef GAME_H #define GAME_H class Game { public: static int const m_rows = 6; static int const m_cols = 7; Game(); int **getBoard(); private: int m_board[m_rows][m_cols]; }; #endif // GAME_H ``` Now what I would like is something like this in game.cpp (cause I thought array name without brackets is a pointer to first element, obviously it doesn't work with 2d arrays) : ``` int **Game::getBoard() { return m_board; } ``` So that i can put this for example in my main.cpp: ``` Game *game = new Game; int board[Game::m_rows][Game::m_cols] = game->getBoard(); ``` Can anybody help me, what should i put in my game.cpp ? Thanks!