Question

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;

  }
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top