0

I would like to know how I can generate a random string for a member of a struct and assign this value to the member of the struct.

My struct is defined this way:

struct student{
       int key;
       char name[25];
}

I already generated random numbers of the member "key" of struct.
Part of the code of the method:

    struct student s;
    int r = rand() % 5000;
    s.key=r;

Note: With srand(time(NULL)); defined in main().

How I do it for s.name?

Zombie
  • 321
  • 3
  • 6
  • 16
  • Does [this](http://stackoverflow.com/q/25759513/62576) help? – Ken White Dec 30 '14 at 17:01
  • Or [this](http://stackoverflow.com/questions/15767691/whats-the-c-library-function-to-generate-random-string) -- and so on. Hard to tell what your problem is. – Jongware Dec 30 '14 at 17:02

2 Answers2

2

rand() returns int so you can't use rand() to assign random strings to your struct member.

You can do something like below using rand() to generate random strings.

char a[]="abcde...z";

for(i=0;i<20;i++)
{
   int r = rand() %26;
   s.name[i] = a[r];
}
s.name[20] = '\0';

After the loop makes sure you NULL terminate the string.

Gopi
  • 19,784
  • 4
  • 24
  • 36
1

This will generate random string of lowercase characters

void
generate_random_string(char *string, size_t length)
{
    size_t i;
    for (i = 0 ; i < length - 1 ; i++)
        string[i] = rand() % ('z' - 'a') + 'a';
    string[length - 1] = '\0';
}

just pass your struct member to it like this

generate_random_string(s.name, sizeof(s.name));
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Thanks! But how do I assign the value of "generate_random_string(s.name, sizeof(s.name))" to s.name? – Zombie Dec 30 '14 at 17:14
  • You don't need to assign the value (you actually can't), you are writing into the array directly. You pass a pointer to the array in `generate_random_string(s.name, sizelf(s.name))`. So you write it's content inside the function. The argument `string` in function `generate_random_string()` points to the same location in memory that `s.name` points to. – Iharob Al Asimi Dec 30 '14 at 17:16