Search code examples
crandomsrand

srand() is not working below initialization of array randomly


Below but it always gives me 42 as SIZE. I wanted to randomise SIZE with srand(time(NULL)) but obviously it is not working because it is below randomisation of SIZE. When I try to add it before randomization of SIZE, compiler yells at me. Do you have any ideas how to correct it?

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; 

Solution

  • You need to call srand() before you call rand() to initialize the random number generator.

    You can try srand( time( NULL ) ) which will give you a different result once per second. If you need it to be more variable than that, then you will have to come up with a better way to seed the number generator.

    int i,numberToBeFound;
    int SIZE;
    int *array2;
    
    srand( time( NULL ) );
    
    SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
    array2 = malloc(sizeof(int)*SIZE);
    
    for(i=0;i<SIZE;i++)     //fill the array with random numbers
        array2[i]=rand()%100; 
    

    PS: You should not cast malloc() in C -- see this post.