3

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.

8
  • 2
    pointer to a static array.. where's that? Commented Feb 8, 2015 at 21:30
  • I forget the static keyword, but the error keeps. Commented Feb 8, 2015 at 21:32
  • do you definitely want an array of pointers to int (not an array of ints) ? Commented Feb 8, 2015 at 21:32
  • 1
    To return a static array, first declare a static array. Commented Feb 8, 2015 at 21:33
  • 1
    That function looks like a global variable in disguise. Commented Feb 8, 2015 at 21:38

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You're better off use std::array

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.