Getter returning 2d array in C++

旧巷老猫 提交于 2019-12-01 11:07:51

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!