c - srand() is not working below initialization of array randomly -


below gives me 42 size. wanted randomise size srand(time(null)) not working because below randomisation of size. when try add before randomization of size, compiler yells @ me. have ideas how correct it?

int i,numbertobefound; int size=(rand()%100)+1; // size can in range [1 100] int *array2 = (int*) malloc(sizeof(int)*size);  srand(time(null));  for(i=0;i<size;i++)     //fill array random numbers     array2[i]=rand()%100;  

you need call srand() before call rand() initialize random number generator.

you can try srand( time( null ) ) give different result once per second. if need more variable that, have come better way seed number generator.

int i,numbertobefound; int size; int *array2;  srand( time( null ) );  size=(rand()%100)+1; // size can in range [1 100] array2 = malloc(sizeof(int)*size);  for(i=0;i<size;i++)     //fill array random numbers     array2[i]=rand()%100;  

ps: should not cast malloc() in c -- see this post.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -