使用malloc
函数动态分配了一个足够存储密码的字符数组,并使用time
函数获取当前时间作为随机数种子。然后,使用循环和取模运算生成随机索引,从字符集中选择字符,并将其存储到密码数组中。最后,添加字符串结束符并返回密码数组。在main
函数中,用户可以输入密码的长度,然后调用generate_password
函数生成动态密码,并打印出来。最后,使用free
函数释放动态分配的内存。你可以根据自己的需求进行修改和扩展。
rand()与srand()用处:简单来说rand()生成的是伪随机数,是一个数值按照公式推算出来的,也就是种子。种子在计算机启动时是随机的,之后就不变了,根据种子推算出进来随机数也就是定值了。所以可以使用当前时间作为随机数种子。
srand(time(NULL));
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char* generate_password(int length) {
char* password = (char*)malloc((length + 1) * sizeof(char));
char characters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
int characters_length = sizeof(characters) - 1; // 减1是为了排除字符串末尾的空字符
srand(time(NULL)); // 使用当前时间作为随机数种子
for (int i = 0; i < length; i++) {
int random_index = rand() % characters_length;
password[i] = characters[random_index];
}
password[length] = '\0'; // 添加字符串结束符
return password;
}
int main() {
int length;
printf("请输入动态密码的长度:");
scanf("%d", &length);
char* password = generate_password(length);
printf("生成的动态密码是:%s\n", password);
free(password); // 释放动态分配的内存
return 0;
}
运行示例: