I'm trying to use C's rand()
to initialize random inputs for a pseudo-random number generator. Due to constraints of a PRNG testing library I'm using, my generator function cannot accept any parameters, so it seems like I'll need to store the initial values as global variables.
Ideally, I would seed the generator with srand(time(NULL))
, but this throws the "initializer element is not a compile-time constant" error when I try to do it globally.
What's the most straightforward way to do this? So far I've come up with passing the global variables into a function and doing the work there, like this:
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;
}
However, when I try to access my values in main, I get a EXC_BAD_ACCESS
error in Xcode:
int main (void)
{
seed(w, x, y, z);
printf("%i", *w); // throws error
...
}
... which I'm guessing has something to do with scope and the memory being freed before I want it to be. Don't have a ton of experience with C, but is this the right approach? If so how can I fix this error?
Thanks!