0

I want to fill 2 arrays with random numbers, i have to use srand(time(NULL)), but when i do the arrays have the same numbers.I created the second array through a function so the time will be different but again the arrays have the same numbers.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int stand(int *arr1,int n)
{
 int i,*arr2;
 arr2=array1(n);
 for(i=0;i<n;i++)
    printf("A= %d\n",*(arr1+i));

 printf("\n");

 for(i=0;i<n;i++)
    printf("b= %d\n",*(arr2+i));

}

int array1(int n)
{
 int i,*pinx;

 pinx = (int*) malloc(n*sizeof(int));

 srand(time(NULL));
 for(i=0;i<n;i++)
    *(pinx+i)=rand()%21+30;
 return pinx;

}

int main()
{
  int *arr1,n,i;

  printf("Give size: ");
  scanf("%d",&n);

  arr1=(int*) malloc(n*sizeof(int));

  srand(time(NULL));
  for(i=0;i<n;i++)
    *(arr1+i)=rand()%21+30;

  stand(arr1,n);

  return 0;

  }
Manuel Pap
  • 1,309
  • 7
  • 23
  • 52
  • possible duplicate of [Why do I get the same result with rand() every time I compile and run?](http://stackoverflow.com/questions/1783629/why-do-i-get-the-same-result-with-rand-every-time-i-compile-and-run) – P.P Mar 08 '14 at 13:32
  • 1
    seed only once is enough – phuclv Mar 08 '14 at 13:36
  • i don't think so, Joachim Isaksson gave me the answer that i was looking for, straight forward answer – Manuel Pap Mar 08 '14 at 13:37
  • Does this answer your question? [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – phuclv Oct 17 '20 at 05:04
  • how's that different from my comment above? I said srand should be called only once – phuclv Oct 17 '20 at 05:04

2 Answers2

3

time(NULL) returns the time in seconds. If both calls to srand(time(NULL)); run within the same second, srand gets the same value both times and initializes the random number generator to generate the same sequence of random numbers.

Just call srand once at the start of the program and remove the other use and things should work as you expect.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

You have probably set the same seed time(NULL) for both calls assuming both of them gets called within the same second of time. You should set a different seed, if you want to get a different set of random numbers.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34