最近学习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个数是:367179024
> 第7个数是:367179024
> 第8个数是:367179024
> 第9个数是:367179024
开始百思不得其解,后来才发现是在把种的种子srand((unsigned)time(NULL))写进了for循环里面,由于程序运行很快,导致每次取的时间都是一样的,改了之后就正常了。
/**********callback_function**********/
第0个数是:869206759
第1个数是:1301008690
第2个数是:1740163573
第3个数是:1832010944
第4个数是:259725898
第5个数是:1600855698
第6个数是:1086908728
第7个数是:31007497
第8个数是:1935517370
第9个数是:1664589043
本文代码来自菜鸟驿站:https://www.runoob.com/cprogramming/c-fun-pointer-callback.html
来源:https://blog.csdn.net/weixin_41308065/article/details/100804625