0

I want to set new seed every time when function is called.

I have tried implementing srand(time(NULL)) in function, that uses rand(). But that doesn't work. I also tried to implement srand(rand()), but every time array is generated it's elements is the same.

I have also tried adding one function (my_init()):

void my_init()
{
    srand(time(NULL));
}
void fillArray(int arr[], int n)
{
    srand(rand());
//    srand(time(NULL));
    for(int i = 0; i < n; ++i)
    {
        arr[i] = rand() % 100;
    }
}
KazlLaur
  • 63
  • 6
  • 5
    *I want to set new seed every time when function is called.* No, you don't. See [`srand()` — why call it only once?](https://stackoverflow.com/questions/7343833) – Steve Summit Nov 29 '22 at 15:47
  • @SteveSummit oh, I get it now. Solved the problem. Thank you. – KazlLaur Nov 29 '22 at 15:52
  • 1
    `srand(time(NULL))` will make `rand()` generate *exactly* the same value if called twice in one second. Seed once, and if you need it unpredictable for security reasons, please, *please* do not use `rand()`. – tadman Nov 29 '22 at 15:58
  • 2
    Welcome to SO. This question seems to be solved, but for future questions please keep in mind that "But that doesn't work." is not a useful description of what is happening. Instead better tell precisely what you expect to happen and what happens instead. – Gerhardh Nov 29 '22 at 16:05

0 Answers0