Currently I'm trying to write just a simple program to generate a string of random characters to represent a name. Calling it once produces what I want, however if I call the function again to make the last name, I get the same result as the first name, length and everything. I currently seed rand at the top with time(), so I'm not sure what's wrong/what I can do. Any help would be appreciated, thanks for your time.
My code is as follows:
int main(void)
{
srand(time(NULL));
int randomNum = 0;
char firstName[12] = { 0 };
char lastName[36] = { 0 };
char fullName[50] = { 0 };
/*for (int j = 0; j < 20; j++)
{
*/ randomNum = rand() % 10 + 2;
strcpy(firstName, generateName(randomNum));
printf("First: %s\n", firstName);
randomNum = rand() % 34 + 2;
strcpy(lastName, generateName(randomNum));
printf("Last: %s\n\n", firstName);
//strcat(fullName, firstName);
//strcat(fullName, " ");
//strcat(fullName, lastName);
//}
//getchar();
return 0;
}
And the generateName function is as follows:
char* generateName(int length)
{
char* randomName = NULL;
randomName = (char*)malloc(sizeof(char) * (length + 1));
if (randomName)
{
randomName[0] = rand() % 26 + 65;
for (int i = 1; i < length; i++)
{
randomName[i] = rand() % 26 + 97;
}
randomName[length] = '\0';
}
return randomName;
}
Again, thanks for your time.
generateName
. – James McLaughlin