我正在通过书 rn 学习 C,我正在尝试制作一个密码生成器 j4f,但我不知道如何获得随机字符。我还希望能够说出我想要多少个字符并且它应该能够从函数返回。
最佳答案
假设使用 ASCII,类似这样的东西应该可以工作:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *randpw(int len) {
char *tmp = malloc(len + 1); // +1 so there's room for null terminator
for (int i = 0; i < len; i++) {
/*
choose a character between 32 and 126, inclusive,
and put the character into the string.
*/
tmp[i] = (rand() % (126 - 32)) + 32;
}
tmp[len] = '\0'; // include null termination on string.
return tmp;
}
int main(void) {
srand( time( NULL));
char *pwd = randpw(15);
printf("%s\n", pwd);
free(pwd);
return 0;
}
每个字符的范围为 32 到 126。如果您查看 ASCII 表,您会发现这些是可供选择的合理字符。
此函数将分配内存,并返回一串随机字符,无论您指定的长度如何。
关于c - 从函数中获取随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657771/