c - 生成 a-z 的随机字母

标签 c

我正在尝试创建一个程序,该程序将生成 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/

相关文章:

c - 查找线程堆栈大小

c++ - 如何在 *C* 中围绕命令行程序编写 GUI 包装器?

c - 如何将变量值传递给 C 中的数组

c - 以下 MPI 程序通过矩形面积求和法计算曲线下面积的错误是什么

c - 通过引用调用的行为

使用定时器处理 C 信号

关于 C 中 malloc 和 calloc 函数的混淆

c - 调整 argVector

c - 解码数据包 - 广播或多播

c - 你如何像Python一样在C中乘以一个字符?