1
votes

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;
                }
            }
        }
    }
}
2
Just commenting on code: Since you have an error case, you should not modify *counter like that in error case. Use a temp int tmp_count = *counter; variable, and assign it back to *counter only if function succeeded. Alternatively, make it abort(); if malloc fails, or something. Avoid producing "partial" result (av=null but *counter is still modified). - hyde
Try to understand pointer-dereference and indexing. *(av + pos++) = 3*i + j + 1; is the same as av[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. - wildplasser
@hyde: You're right, but that was a quick check of malloc, I'm not done with it yet. :) - sotirelisc
@wildplasser: Is there something wrong with the parentheses? - sotirelisc
No, there is nothing wrong with them. But most people tend to reduce the number of parentheses, just because it is easier to read with fewer ((.)(.)). - wildplasser

2 Answers

2
votes

In this function, av is a pointer passed by copy. So when you change the value of your pointer inside the function, the original pointer won't be modified.

There are two possibilities :

  • use a pointer to pointer (int **av);
  • return the allocated pointer (return av).

So either:

void availableMoves(int array[][3], int **av, int *counter);

Or:

int *availableMoves(int array[][3], int *av, int *counter)

And the call:

availableMoves(array, &av, &counter);
av = availableMoves(array, av, &counter);
2
votes

use double pointer for your dynamic array int **av instead of int *av

void availableMoves(int array[][3], int **av, int *counter)

and into the function change av by *av