我正在尝试创建一个程序,该程序将生成 a-z 的一系列随机字母。由于某种原因,它不起作用,并且它也打印其他符号。我知道我如何使用 put 存在一个问题,因为不仅有一个序列,还有它们的“大小”,但我这样做只是为了检查字母生成器是否实际工作,所以我现在想关注这一点。但是,欢迎对代码提出任何建议:)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *randomString(int minSize, int maxSize);
void printStrings(char **strArray, int strArraySize);
int main()
{
int size, i;
char **ptr;
printf("Type in the number of characters you would like to be used: ");
scanf("%d", &size);
ptr = malloc(size*sizeof(ptr));
if (ptr==NULL) {
printf("Cannot allocate memory. The program will now terminate.");
return -1;
}
for (i=0; i<size; i++)
ptr[i] = randomString(5, 20);
ptr[i] = '\0';
puts(*ptr);
return 0;
}
char *randomString(int minSize, int maxSize)
{
time_t t;
srand((unsigned) time(&t));
char *rndSize, *p;
int i;
rndSize = (char *)malloc(21);
p = rndSize;
for (i = minSize + rand() % 16; i<=maxSize && i>=minSize; i++)
*p++ = 97 + rand() % 26;
return rndSize;
}
最佳答案
这是一个工作示例。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *randomString(int minSize, int maxSize);
void printStrings(char **strArray, int strArraySize);
int main()
{
time_t t;
srand((unsigned) time(&t));
int size, i;
char **ptr;
printf("Type in the number of characters you would like to be used: ");
scanf("%d", &size);
ptr = malloc(size*sizeof(*ptr));
if (ptr==NULL) {
printf("Cannot allocate memory. The program will now terminate.");
return -1;
}
for (i=0; i<size; i++)
{
ptr[i] = randomString(5, 20);
puts(ptr[i]);
}
return 0;
}
char *randomString(int minSize, int maxSize)
{
char *rndSize, *p;
int i;
rndSize = (char *)malloc(maxSize+1);
p = rndSize;
for (i = minSize + rand() % 16; i<=maxSize; i++)
*p++ = 97 + rand() % 26;
*p = '\0';
return rndSize;
}
它在每个序列后添加 NUL 终止字符。它还逐个打印每个序列。随机数生成器初始化已放在 main 中,以避免每次都获得相同的序列。在我看来,t
尚未初始化仍然很奇怪。仍有很多修复/改进。
关于c - 生成 a-z 的随机字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078485/