0

I'm working on my personal project. What i wanna know is this

class Tile
{
private:
    char mBlockTile[22][24];

I just wanna return that 2D array through getter, like

char* GetBlockTile()
{
  return mBlockTile;
}

But i totally don't know how to do this. I modified data type of the function many times and tried to return 2D array, but it doesn't work. :( Please help as quickly as possible. Thanks!

underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • 1
    Have you considered [`std::array`](http://en.cppreference.com/w/cpp/container/array)? It allows you to use arrays just like any other object. – François Andrieux Jul 19 '17 at 13:50
  • If you use `std::array` it becomes pretty easy. – NathanOliver Jul 19 '17 at 13:50
  • 1
    The code snippet tool doesn't work for c++. It's mostly for web stuff that can be rendered in browser. – François Andrieux Jul 19 '17 at 13:51
  • You should return by reference, preferably const, not by pointer (which is needless if it cannot be null) or value (the caller can make their own copy if they need one for some reason). `std::array` can do either, though – underscore_d Jul 19 '17 at 13:51

2 Answers2

5

You should use std::array if you can:

#include <array>

class Tile {
    std::array<std::array<char, 24>, 22> mBlockTile;
    auto& GetBlockTile() { // return a reference, you don't want a copy
        return mBlockTile;
    }
};

If you cannot use std::array, the old way (prior to c++11 and auto / decltype) would be:

char (*GetBlockTile())[24] {
    return mBlockTile;
}

Or a reference:

char (&GetBlockTile())[22][24] {
    return mBlockTile;
}
// (freaky) const version
const char (&GetBlockTile() const)[22][24] {
    return mBlockTile;
}

...at which point you probably want to start using a typedef:

typedef char tBlockTile[22][24];
tBlockTile mBlockTile;

const tBlockTile& g() const {
    return mBlockTile;
}
Holt
  • 36,600
  • 7
  • 92
  • 139
2

Ugly syntax:

class Tile
{
private:
    char mBlockTile[22][24];
public:
    char (&getBlock()) [22][24] { return mBlockTile; }
};

With using

class Tile
{
private:
    char mBlockTile[22][24];
    using blockType = char[22][24];
public:
    blockType& getBlock() { return mBlockTile; }
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302