0
votes

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.

2
Platform, compiler, runtime library? Unrelated, but you're leaking memory by not freeing the result of generateName.James McLaughlin
Sorry, as I'm a relatively new programmer, I'm using Visual Studio 2013 on Windows 10, I hope that answers your question.Hayden Taylor
I am a complete fool, I totally didn't see what I was printing the second time around.Hayden Taylor

2 Answers

4
votes

I think you generate the last name all right, but when you print it:

printf("Last: %s\n\n", firstName);
                       ^here

See? You are printing the first name again!!

Just do:

printf("Last: %s\n\n", lastName);

PS: The best thing about VisualStudio is its integrated debugger. You should learn to use it, and these kind of errors will show themselves.

0
votes

You are printing firstName in the second print statement in stead of lastName :D Otherwise your code is fine - produces a new name in each run.

printf("Last: %s\n\n", firstName);