程序没有输出完整的字符串

Program does not output the complete string

我正在学习 C,在打印我随机生成的内容的字符串时遇到了问题。

下面的代码只打印出前 89 个字符,我需要得到全部 1000 个字符。

我曾尝试搜索类似问题并查找 c 教程,但找不到解释。感谢任何帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    srand(1000);
    int i;
    char *niz;
    niz = calloc(1001, sizeof(char));
    for (i = 0; i < 1000;i++){
        int randbroj = rand() % 62;
        if (randbroj < 10){
            niz[i] = randbroj + 48;
        }
        if (randbroj > 10 && randbroj < 36){
            niz[i] = randbroj + 55;
        }
        if (randbroj > 35 && randbroj < 62){
            niz[i] = randbroj + 61;
        }
    }
    niz[1000] = '[=10=]';
    printf("%s",niz);
    return 0;
}

calloc()将return0填满内存。因此,在您的情况下,如果 if 的 none 检查匹配(在 randbroj == 10 的情况下发生),niz[i] 将不会获得任何新值并且保留默认值 0,即空终止符的值。

你的字符串到此结束。

解决方案:添加对所有 个可能值的检查,包括 10。