How to return a static array pointer

ぃ、小莉子 提交于 2020-01-14 20:01:28

问题


I'm trying to create a function that creates a bidimensional array with default values. And then, the function should return the pointer for that static array.

int* novoTabuleiro() {

    static int *novoTabuleiro[LINHAS][COLUNAS];

    //Some changes

    return novoTabuleiro;
}

And then I want to do something like this:

int *tabuleiroJogador = novoTabuleiro();

What is wrong in the function above. The error I receive is "return from incompatible pointer type". Thanks.


回答1:


Your comments indicate that the array is meant to be a 2-D array of ints:

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

Due to array-pointer decay, the expression novoTabuleiro in the return statement means the same as &novoTabuleiro[0].

The type of novoTabuleiro[0] is "array [COLUNAS] of int" , i.e. int [COLUNAS]. So a pointer to this is int (*)[COLUNAS].

That means your function needs to be:

int (*func())[COLUNAS]  {

and the calling code would be:

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

It would be less confusing to use a different name for the function than you use for the name of the array within the function.




回答2:


You're better off use std::array

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


来源:https://stackoverflow.com/questions/28399577/how-to-return-a-static-array-pointer

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