我需要函数drop_balls来返回一个数组,以便我可以让我的下一个函数使用该数组。我需要它接受一个整数作为参数,然后返回一个int数组,以便它可以在我将要制作的另一个函数中使用。我一直在读它只能作为指针传递,但我完全不知道如何编码,有人可以帮助我。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Prototype for drop_Balls, int parameter is number of balls being dropped */
int [] drop_balls(int);
/* Gets the number of balls that need to be dropped by the user */
int get_num_balls();
int main()
{
drop_balls(get_num_balls());
}
int get_num_balls()
{
int num_balls;
printf("How many balls should be dropped? ");
scanf("%d", &num_balls);
/* Ensure that it is atleast one ball */
while(num_balls <= 0)
{
printf("You have to drop at least one ball! \n ");
printf("How many balls should be dropped? ");
scanf("%d", &num_balls);
}
/* Return the number of balls that will be dropped */
return num_balls;
}
int [] drop_balls(int num_balls)
{
/* Keeps track of how many balls landed where */
int ball_count[21];
/* What number ball are we on */
int ball_num = 0;
/* Seed the generator */
srand(time(NULL));
/* Do the correct # of balls */
for(ball_num = 0; ball_num < num_balls; ball_num++ )
{
/* Start at 10 since its the middle of 21 */
int starting_point = 10;
/* Bounce each ball 10 times */
for(starting_point = 10; starting_point > 0; starting_point--)
{
int number;
/* Create a random integer between 1-100 */
number = rand() % 100;
/* If its less than 50 bounce to the right once */
if(number >= 50)
{
starting_point++;
}
/* If its greater than 50, bounce to the left once */
else
{
starting_point--;
}
}
/* Add one to simulate one ball landing there */
ball_count[starting_point]++;
}
return ball_count;
}
答案 0 :(得分:0)
它不完全确定你想要实现什么,但如果你想将一个整数数组balls
传递给函数drop_balls
,它将被声明为:
void drop_balls(int **balls);
int main ()
{
int *balls; /* This is your array of balls*/
/* Allocate memory for `number_of_balls` number of balls */
balls = malloc(number_of_balls * sizeof(*balls));
if (balls == NULL)
printf("Error: failed to allocate memory");
/* call the function by passing the pointer to your array of balls */
drop_balls(&balls);
free(balls);
return 0;
}
答案 1 :(得分:0)
您不能返回在函数中声明为局部变量的数组。它存在于堆栈中,一旦函数返回它将不再存在。你将返回数组 的地址,这将是不好的。
相反,您需要使用malloc,
在堆上创建数组并返回指向它的指针。您将需要检查此指针是否为NULL,
,并且您需要调用free
以在完成后释放内存。您还应该将函数的返回类型更改为int *
。
答案 2 :(得分:-1)
返回数组的函数示例是malloc()
,一个标准的库函数。您可以编写自己的函数来分配数组,对其执行某些操作并将其返回给调用者:
int *function_returning_an_array_of_size_n(int n)
{
int *array = (int*)malloc(n * sizeof(int));
// do something useful with the array
// ...
return array;
}
将数组作为参数的函数示例是free()
,同样是标准库函数。
以下是编写接收数组作为参数的函数的方法。
void function_receiving_an_array_and_size_n(int *array, int n)
{
// Do something with array. If accessing elements beware the array size violation.
}
我传递了一个额外的参数,数组大小。在不知道大小的情况下访问数组元素会很危险。