c - srand() 在数组随机初始化下不工作

标签 c random srand

但它总是给我 42 作为 SIZE。我想用 srand(time(NULL)) 随机化 SIZE 但显然它不起作用,因为它低于 SIZE 的随机化。当我尝试在 SIZE 随机化之前添加它时,编译器对我大喊大叫。你知道如何纠正它吗?

int i,numberToBeFound;
int SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
int *array2 = (int*) malloc(sizeof(int)*SIZE);

srand(time(NULL));

for(i=0;i<SIZE;i++)     //fill the array with random numbers
    array2[i]=rand()%100; 

最佳答案

int i, numberToBeFound;
int SIZE=0;
int* array2=0;

srand(time(NULL));

SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
array2 = (int*) malloc(sizeof(int)*SIZE);

for(i=0;i<SIZE;i++)     //fill the array with random numbers
    array2[i]=rand()%100;

它是古老的 C(C89 或更早版本)。因此,声明您的局部变量,然后初始化它们,最后根据需要使用它们。

关于c - srand() 在数组随机初始化下不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16345288/

相关文章:

c - 如何让GDB识别bi-endian代码?

c - 从数组中打印随机选择

mysql - 在MySQL中使用REGEXP为搜索引擎随机匹配关键词

Java - 对 Math.random() 的多次调用搞乱了循环

c - 优先规则 - 使用括号和除法与 srand 获取 float 时出现问题

C - 初始化结构成员 - 指针数组。第二个元素的值不正确

c - 为什么输出是一个框中的问号而不是数字

java - 为什么这个 if 语句不能正确运行

c - 如何避免使用 rand 和 srand 得到重复的数字?

c++ - 随机数和编程逻辑