为随机全局变量播种rand()

时间:2017-09-07 04:45:07

标签: c random

我正在尝试使用C rand()初始化伪随机数生成器的随机输入。由于我正在使用的PRNG测试库的限制,我的生成器函数不能接受任何参数,所以我似乎需要将初始值存储为全局变量。

理想情况下,我会使用srand(time(NULL))为生成器播种,但是当我尝试全局执行时,这会抛出“初始化元素不是编译时常量”错误。

最简单的方法是什么?到目前为止,我已经将全局变量传递给函数并在那里完成工作,如下所示:

unsigned int* w;
unsigned int* x;
unsigned int* y;
unsigned int* z;

void seed (unsigned int* first, unsigned int* second, unsigned int* third, unsigned int* fourth)
{
    srand((unsigned int) time(NULL));
    unsigned int a = rand();
    unsigned int b = rand();
    unsigned int c = rand();
    unsigned int d = rand();

    first =  &a;
    second = &b;
    third = &c;
    fourth = &d;
}

但是,当我尝试在main中访问我的值时,我在Xcode中出现EXC_BAD_ACCESS错误:

int main (void)
{
    seed(w, x, y, z);
    printf("%i", *w);     // throws error
...
}

...我猜测它与范围有关,而且在我想要之前释放内存。没有大量的C经验,但这是正确的方法吗?如果是这样,我该如何解决此错误?

谢谢!

3 个答案:

答案 0 :(得分:2)

您正在指定仅存在于堆栈中的值的指针,而不是像您认为的那样推回原因。一旦该堆栈超出范围,您就会陷入危险的境地。

以下是它的编写方式:

void seed (unsigned int* a, unsigned int* b, unsigned int* c, unsigned int* d)
{
    srand((unsigned int) time(NULL));
    *a = rand();
    *b = rand();
    *c = rand();
    *d = rand();
}

int main() {
   // Note: These can be global, they're just put here for convenience
   // Remember, global variables are bad and you want to avoid them.
   unsigned int a, b, c, d;
   seed(&a, &b, &c, &d);

   // ...
}

答案 1 :(得分:1)

变量a, b, c, d的范围在种子函数内,因此在函数外部访问这些引用将导致意外结果。
您需要传递变量地址以填充或为seed函数中的每个数字分配内存。

尝试以下代码段

unsigned int w;
unsigned int x;
unsigned int y;
unsigned int z;

void seed (unsigned int* first, unsigned int* second, unsigned int* third, unsigned int* fourth)
{
    srand((unsigned int) time(NULL));

    *first =  rand();
    *second = rand();
    *third = rand();
    *fourth = rand();
}


int main (void)
{
    seed(&w, &x, &y, &z);
    printf("%i", w);
}

答案 2 :(得分:0)

EXC_BAD_ACCESS是因为您要将seed()的局部变量地址分配给指针

seed()返回时,这些变量及其地址无效