1

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]);
}
2
  • Change *b=(char*)malloc(sizeof(char*)*10); with b[j]=(char*)malloc(sizeof(char*)*10); Commented Sep 2, 2014 at 12:07
  • Don't use rand. Ever. Commented Sep 2, 2014 at 12:08

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. I haven't noticed the b[j] = s;. strcpy will do the job.
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.