JMS
JMS

Reputation: 281

Creating multiple random strings in C

I have written a code which creates multiple random strings. But every time I print it, only the last string is printed multiple times even though different strings are created every time. Can anyone tell me what I'm doing wrong.

    static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";

    char s[5],*b[5] ;

    int num =0;
    for(int j=0;j<5;j++)
    {
        *b=(char*)malloc(sizeof(char*)*10);
        for (int i = 0; i < 4; ++i)
        {
            num = rand() % (sizeof(alphanum) - 1);
            s[i] = alphanum[num];
        }

        s[4] = 0;
        printf("%s\t",s);
        b[j] = s;
    }

    for(int j=0;j<5;j++)
        printf("\n%s",b[j]);
}

Upvotes: 1

Views: 255

Answers (3)

CollioTV
CollioTV

Reputation: 686

I think your should read the man 3 rand

In facts you have to "seed" your rand by calling void srand(unsigned int seed); one time in the beggining of your application

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

First of all, doing e.g. *b is the same as *(b + 0) which is the same as b[0]. That means that when you allocate memory you assign it to the same entry all the time.

Secondly, last in the loop you overwrite the pointer and make b[j] point to s, all the time. So all pointers in b will point to the same s. That's why all your strings seems to be the same.

Thirdly, you don't need to allocate dynamically in the loop, as all strings are of a fixed size. Instead declare b as an array of arrays of characters:

char b[5][5];

Then instead of assigning the pointer, you copy the string into the correct entry in b.


Lastly, and for future reference, don't cast the return of malloc.

Upvotes: 0

Callidior
Callidior

Reputation: 2904

Assuming that you've seeded the random number generator with, for instance, srand(time(NULL));, so that it will generate different random number sequences on each run of the program, there is one more flaw in your code:

s is a pointer to an array of characters. With the assignment b[j] = s;, you only assign b[j] the pointer (memory location) of s, but not the contents of s. Since the memory location of s does not change, all entries of b contain the same reference to the same string s, which has been changed multiple times. To copy the current content of s to b[j], use strcpy(), like this.

strcpy(b[j], s);

Upvotes: 3

Related Questions