My code initializes a pointer to a random name. The random name is randomly selected by using the rand function.
I have noticed that the rand function does not quite do what I want it to do. In the following code, it initializes all the pointers with the same name! I suspect this has do to with the rand function basing its selection on the time function. If it initializes all the pointers at once, it will produce the same random number!? I'm sure it takes time for the time stamp to produce another number right? I can fix the code by running the initializations in a loop but I would like to know another way to fix as sometimes it takes a few seconds to work through the loop.
For reference:
#include <stdio.h>
#include <stdlib.h>
int random_number(int, int);
const char *random_name();
//----------------------------------------------------------------
int main(void)
{
const char * kg = NULL;
const char * ke = NULL;
const char * dg = NULL;
const char * de = NULL;
kg = random_name();
ke = random_name();
dg = random_name();
de = random_name();
printf("kg=%s\nke=%s\ndg=%s\nde=%s\n", kg, ke, dg, de);
return 0;
}
//----------------------------------------------------------------
const char *random_name(int x)
{
const char *names[7] =
{"Bob", "Billy", "Buck", "Bobby", "Bill", "Billy Bob", "Bobi"};
int roll = random_number(0,7);
return names[roll];
}
//----------------------------------------------------------------
int random_number(int min, int max)
{
int roll;
int maximum = max - min;
srand(time(NULL));
roll = (rand() % maximum) + min;
return roll;
}