Click here to Skip to main content
14,453,670 members
Rate this:
Please Sign up or sign in to vote.
See more:
How do I generate random string using the characters of length(len)? in C

void gen_random(char *s, const int len)
{
    char charset[] = "0123456789!\"#$%&'()*+-/. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
}


What I have tried:

I tried doing char randomString
Posted
Updated 6-Sep-19 5:37am
v2
Comments
Patrice T 6-Sep-19 9:26am
   
Elaborate!
The question makes no sense.
Rate this:
Please Sign up or sign in to vote.

Solution 1

   
Comments
KarstenK 7-Sep-19 15:29pm
   
RTFM - the epic answer.

scnr ;-)
Rate this:
Please Sign up or sign in to vote.

Solution 2

Richard has given you the link you need: now all you have to do is use it.
How? Simple: You function gets two parameters, a pointer and a
Use a loop that iterates len times, and inside the loop call the rand function. That returns an integer value, so use the % operator (which returns a remainder) to give you a value between 0 and the length of charset minus one. That is your random index into charset - so fetch the character at the index, and add it to the output and increment the pointer.

You may need to add a null value after the loop if it's to be treated as a string, but that will depend on the defintion of your function. If there aren't enough characters in the memory area passed to your function, don't add it!
   
Comments
k5054 6-Sep-19 14:40pm
   
Don't forget about srand(). Note that the code given on the MS Docs link does have one issue: because it uses time() to seed rand, it can produce identical results if the program is run more than once within the same second. In general, there's probably a pretty small chance of that happening, but it is something to be aware of, should circumstances require.
Rick York 6-Sep-19 23:47pm
   
If that matters you could use timeGetTime() and get milliseconds. The chance of the program starting twice in the same millisecond seems exceedingly remote to me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100