how to make random string in c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *generateRandomString(int length) {
char *charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char *randomString = malloc(length + 1);
if (randomString) {
for (int i = 0; i < length; i++) {
int index = rand() % 62;
randomString[i] = charset[index];
}
randomString[length] = '\0';
}
return randomString;
}
int main() {
srand(time(0));
int length = 10;
char *randomString = generateRandomString(length);
if (randomString) {
printf("Random String: %s\n", randomString);
free(randomString);
}
return 0;
}
Explanation
Include Necessary Libraries
- Include the necessary standard libraries stdio.h
, stdlib.h
, and time.h
for input/output, memory allocation, and time functions.
Define Function to Generate Random String
- Define a function generateRandomString
that takes an integer length
as input and returns a pointer to a character array.
- Define a character array charset
containing the characters from which the random string will be generated.
- Allocate memory for the random string using malloc
and add 1 to the length to accommodate the null terminator.
- Generate the random string by iterating over the specified length and selecting random characters from the charset
.
- Append the null terminator at the end of the random string.
Main Function
- In the main
function, seed the random number generator using the current time to ensure different random strings are generated on each run.
- Specify the length of the random string.
- Call the generateRandomString
function to obtain a random string and print it.
- Free the memory allocated for the random string to prevent memory leaks.
- Return 0 to indicate successful execution.