无法将char(*)[10]转换为char **作为回报

时间:2011-01-11 00:44:24

标签: c++

  

可能重复:
  Declaring a function that return a 2D array in a header file?

我正在尝试为2D数组提供一个简单的getter函数,我似乎无法找出发送它的正确语法。

目前,我有以下内容:

class Sample
{   
public:
    char **get2D();

private:
    static const int x = 8;
    static const int y = 10;
    char two_d[x][y];
};


char** Sample::get2D()
{
    return  two_d;
};

2 个答案:

答案 0 :(得分:6)

数组数组与指向数组的指针数组不同。在您的情况下,如果没有在公共接口中发布数组的宽度(y),则无法返回正确的类型。没有它,编译器不知道返回数组的每一行有多宽。

您可以尝试以下方法:

class Sample
{   
public:
    static const int x = 8;
    static const int y = 10;
    typedef char Row[y];
    Row *get2D();

private:
    char two_d[x][y];
};

答案 1 :(得分:0)

更好的做法是:

const char& operator()(int x1, int y1)
{
  // Better to throw an out-of-bounds exception, but this is illustrative.
  assert (x1 < x);
  assert (y1 < y);
  return two_d[x][y];
};

这允许您对阵列内部的安全只读访问(可检查!)。