如何返回静态数组指针

时间:2015-02-08 21:29:47

标签: c++ c arrays static

我正在尝试创建一个使用默认值创建二维数组的函数。然后,该函数应返回该静态数组的指针。

int* novoTabuleiro() {

    static int *novoTabuleiro[LINHAS][COLUNAS];

    //Some changes

    return novoTabuleiro;
}

然后我想做这样的事情:

int *tabuleiroJogador = novoTabuleiro();

上述功能有什么问题。我收到的错误是“从不兼容的指针类型返回”。感谢。

2 个答案:

答案 0 :(得分:5)

您的注释表明该数组是一个二维的整数数组:

static int novoTabuleiro[LINHAS][COLUNAS];
return novoTabuleiro;

由于数组指针衰减,return语句中的表达式novoTabuleiro表示与&novoTabuleiro[0]相同。

novoTabuleiro[0]的类型是" int"的数组[COLUNAS] ,即int [COLUNAS]。所以指向这个的指针是int (*)[COLUNAS]

这意味着你的职能需要:

int (*func())[COLUNAS]  {

,调用代码为:

int (*tabuleiroJogador)[COLUNAS] = func();

使用函数的不同名称比使用函数中的数组名称更容易混淆。

答案 1 :(得分:1)

最好不要使用std::array

static std::array<std::array<int, LINHAS>, COLUNAS> novoTabuleiro;
return novoTabuleiro;