1

I have this code I need to write, and I created this function. Irrelevant of what it does for the code, I need it to generate a random number (a) between 0 and (i), an integer with a previously initialized value. Somehow despite seeding, I always get the same number.

I have tried entering a number instead of i and it works properly by giving me a different random number each time I execute. I also tried declaring a new int variable inside in the function and giving it the value of i, but it still doesn't work.

elementptr position_current(elementptr first, int i){
  elementptr current = first;
  int j = 1;

  printf("%d\n", i);
  srand(time(NULL));

  int a = rand() % i;
  printf("%d\n",a);
  for(j=1;j<a;j++){
    current = current->next;
  }

  return current;
}

I expect (a) to get a different value each Time I run the code, however it's always getting the same value(2).
Can someone tell me what could be wrong?

Mike
  • 4,041
  • 6
  • 20
  • 37
marco42001
  • 11
  • 2
  • 2
    You should call `srand()` only once, at the beginning of the program. Subsequent calls to `rand()` will change the seed and produce pseudo-trandom numbers. – M Oehm Apr 24 '19 at 05:58

1 Answers1

2

I'm guessing you're calling this function many times in a single second. Since time only changes once a second, you're reseeding the same value over and over.

Don't call srand over and over. Call it exactly once in your main function, then never call it again, and rand will produce successive values based on that seed one at a time.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271