-2

I'm trying to make a function that creates a personalized array and return the pointer to it. I've the following code:

int (*newArray())[COLUNAS] {

    static int thisIsTheNewArray[LINHAS][COLUNAS];
    /* some changes */
    return thisIsTheNewArray;
}

Then, I have:

int (*tabuleiroJogador)[COLUNAS] = newArray();
int (*tabuleiroComputador)[COLUNAS] = newArray();

The problem here is that if I change tabuleiroJogador I also change tabuleiroComputador. I don't know why this is happenning. I think it's related with the static keyword and it returns always the same instance.

The arrays should be different.

Henrique Dias
  • 182
  • 4
  • 13

3 Answers3

2

static in this context means that the array will maintain it's value between calls to the newArray() function.

If you want a different copy of the array each time newArray is called, you will need to dynamically create it. You will also need to be sure that it is properly deallocated when you are finished.

int* newArray(int lines, int columns)
{
   return malloc(sizeof(int) * lines * columns);
}

int* arr = newArray();
/* later... */
free(arr);

Note: This has slightly different semantics than your original, in that it allocates enough space but the array will be indexed in a single dimension.

Chad
  • 18,706
  • 4
  • 46
  • 63
  • Thank you. This answer (http://stackoverflow.com/questions/917783/how-do-i-work-with-dynamic-multi-dimensional-arrays-in-c) also helped me. – Henrique Dias Feb 09 '15 at 21:03
2

As others have mentioned, you have to use malloc if you want different calls to the function to create different instances.

(Well, you don't have to; you could use a table of static arrays, if you know at the start of the program exactly how many different arrays you need).

The code for malloc could be:

int (*newArray())[COLUNAS]
{
    int (*p)[COLUNAS] = calloc(LINHAS, sizeof *p);
    return p;
}

In case you had overlooked the possibility; the arrays could have been created without using a function:

int tabuleiroJogador[LINHAS][COLUNAS];
int tabuleiroComputador[LINHAS][COLUNAS];

or using malloc:

int (*tabuleiroJogador)[COLUNAS] = calloc(LINHAS, sizeof *tabuleiroJogador);
int (*tabuleiroComputador)[COLUNAS] = calloc(LINHAS, sizeof *tabuleiroComputador);
M.M
  • 138,810
  • 21
  • 208
  • 365
0

static variables in a function share the same memory space across multiple calls, and this is why we love them. This property allows the variable to retain it's value across the calls, giving it global-like functionality. To dynamically allocate memory for your needs, use the specialized functions like malloc.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61