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!
You cannot pass arrays by value into and out of functions. But there’s various options.
(1) Use a
std::array<type, size>(2) Use the correct pointer type.
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.Which means one
int*points to all of them. To get to a row offset, you’d do something like this: