[英]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. 在我的C程序中,我使用带有以下参数的void函数:一个2D int数组,一个用于创建新动态数组的int指针和一个最后一个int指针,它将包含将在功能。 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.
所以使用malloc在函数中创建动态数组,一切正常,直到我在调用函数后在main()中打印它的元素。 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
对动态数组使用双指针
int **av
而不是int *av
void availableMoves(int array[][3], int **av, int *counter)
and into the function change av
by *av
进入功能改变
av
*av
In this function, av
is a pointer passed by copy. 在此函数中,
av
是通过副本传递的指针。 So when you change the value of your pointer inside the function, the original pointer won't be modified. 因此,当您在函数内更改指针的值时,不会修改原始指针。
There are two possibilities : 有两种可能性:
int **av
); int **av
); return av
). 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.