简体   繁体   中英

Returning dynamic array through void function in C

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;
                }
            }
        }
    }
}

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM