我想创建一个名为get_lotto_draw的函数,它将创建一个包含6个随机数的数组,并将它们返回给main。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
get_lotto_draw()
{
int lottery[50];
int u,i,j,temp;
int lotto[6];
srand(time(NULL));
for (i =0; i<49; i++)
lottery[i] = i+1;
for (i =0; i<49; i++)
{
j = (rand()%49)+1;
temp = lottery[i];
lottery[i] = lottery[j];
lottery[j] = temp;
}
for (i =0; i<6; i++)
{
lotto[i] = lottery[i];
}
return lotto;
}
答案 0 :(得分:2)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void get_lotto_draw(int lotto[])
{
int lottery[50];
int u,i,j,temp;
for (i =0; i<49; i++)
lottery[i] = i+1;
for (i =0; i<49; i++)
{
j = (rand()%49)+1;
temp = lottery[i];
lottery[i] = lottery[j];
lottery[j] = temp;
}
for (i =0; i<6; i++)
{
lotto[i] = lottery[i];
}
return ;
}
int _tmain(int argc, _TCHAR* argv[])
{
int lotto[6];
srand(time(NULL));
get_lotto_draw(lotto);
for (int i = 0; i < 6; i ++)
printf ("%d ", lotto[i]);
printf ("\n");
return 0;
}
函数get_lotto_draw
将采用数组&#39; lotto&#39;作为参数 - unsized数组。
如果在函数内部将lotto声明为自动变量,那么当函数结束时 - 自动变量lotto将被删除 - 请查看此link以获取详细信息。
所以你在main中声明了lotto并将它传递给函数。
其他选项包括
我建议在这种情况下使用堆栈(如上所用的自动变量),否则使用malloc / free。
我修正了其他人指出的一些错误
答案 1 :(得分:0)
非常感谢所有帮助过的人。我花了几个小时阅读并了解你提到的事情。我现在已经设法创建了一个能够完成我想要的代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *get_lotto_draw(int n)
{
int i;
int *lotto;
lotto = malloc(n * sizeof(*lotto));
if (lotto == NULL)
return NULL;
int lottery[50];
int u,j,temp;
for (i =0; i<49; i++)
lottery[i] = i+1;
for (i =0; i<49; i++)
{
j = (rand()%49)+1;
temp = lottery[i];
lottery[i] = lottery[j];
lottery[j] = temp;
}
for (i =0; i<6; i++)
{
lotto[i] = lottery[i];
}
return lotto;
}
int main(int argc, char *argv[])
{
int i, n = 6;
int *lotto;
srand(time(NULL));
lotto = get_lotto_draw(n);
if (lotto == NULL)
return -1;
printf("Here is the array: ");
for(i = 0 ; i < n ; i++) {
printf("%d ", lotto[i]);
}
free(lotto);
printf("\n\n");
return 0;
}
答案 2 :(得分:0)
我还发现我可以通过使用static int来做到这一点,因为我有一个set length数组。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *get_lotto_draw(int n)
{
int i;
static int lotto[6];
int lottery[50];
int u,j,temp;
for (i =0; i<49; i++)
lottery[i] = i+1;
for (i =0; i<49; i++)
{
j = (rand()%49)+1;
temp = lottery[i];
lottery[i] = lottery[j];
lottery[j] = temp;
}
for (i =0; i<6; i++)
{
lotto[i] = lottery[i];
}
return lotto;
}
int main(int argc, char *argv[])
{
int i, n = 6;
int *lotto;
srand(time(NULL));
lotto = get_lotto_draw(n);
printf("Here is the array: ");
for(i = 0 ; i < n ; i++) {
printf("%d ", lotto[i]);
}
printf("\n\n");
return 0;
}