In my C program, I use a void function with the following arguments: One 2D int array, one int pointer that will be used to create the new dynamic array and a last int pointer which will hold a number of counts that will occur inside the function. So the dynamic array is created in the function using malloc and everything works okay, until I print its elements in main() after calling the function. What I get is rubbish instead of the numbers I should see. Here's the function code:
void availableMoves(int array[][3], int *av, int *counter)
{
int i, j;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
if (array[i][j] == E)
{
printf("%d ", 3*i + j + 1);
(*counter)++;
}
}
}
av = (int *) malloc(*counter * sizeof(int));
if (av == NULL)
{
printf("ERROR!");
}
else
{
for (i=0; i<*counter; i++)
*(av + i) = 0;
int pos = 0;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
if (array[i][j] == E)
{
*(av + pos++) = 3*i + j + 1;
}
}
}
}
}
*counterlike that in error case. Use a tempint tmp_count = *counter;variable, and assign it back to*counteronly if function succeeded. Alternatively, make itabort();if malloc fails, or something. Avoid producing "partial" result (av=nullbut*counteris still modified).*(av + pos++) = 3*i + j + 1;is the same asav[pos++] = 3*i + j + 1;, but most human readers prefer the second form. Similar for(*counter)++;which could be written as*counter += 1;, avoiding the parentheses.