Search code examples
crandomsrand

Is there a better function than rand()?


I have a program, in C, which creates an array of 1000 integers using a random number from 0-999 and then performs some sort of algorithm on that array. In order to test the algorithm's running time, I try running the program 10000 times, but every time I run it the array is the same for a few arrays and then it changes. I have used the srand() function to feed the seed with the current time, but it still does not help.

Is there an alternative solution to rand() or a way to fix this? My function is:

void getarray(int *ptr1, int size, int option){
    int n;
    srand(time(NULL));
    for(n=0; n<size; n++)
        *(ptr1+n) = *(ptr2+n)= rand()%1000; 
}

Thanks in advance!


Solution

  • You should only call srand once: on program startup.

    Right now, if you call your function multiple times before time changes your sequence will be the same.