最近学习C语言,写了一个将随机数写入数组的回调函数,发现数组中所有的值都是一样的:
/***********回调函数**********/
void populate_array(int *array,size_t array_Size,int (*getNextValue)())
{
size_t i;
for(i = 0; i < array_Size; i++)
{
array[i] = getNextValue();
}
}
//
int getNextRandomValue()
{
//sleep(1);
srand((unsigned)time(NULL));//问题出在这里
return rand();
}
void callback_function()
{
int myarr[10];
int i;
//srand((unsigned)time(NULL));//应该写在这里
populate_array(myarr,10,getNextRandomValue);
for(i = 0;i < 10; i++)
{
printf("第%d个数是:%d \n",i,myarr[i]);
}
printf("\n");
return;
}
函数运行如下
/**********callback_function**********/
> 第0个数是:367179024
> 第1个数是:367179024
> 第2个数是:367179024
> 第3个数是:367179024
> 第4个数是:367179024
> 第5个数是:367179024
> 第6个数是:3