isaric
isaric

Reputation: 305

Program does not output the complete string

I'm learning C and I have encountered a problem when printing out a string which contents I generated randomly.

The code below prints out only the first 89 characters and I need to get the whole 1000.

I have tried searching for similar questions and looking up c tutorials but I could not find the explanation. Any help is appreciated.

#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] = '\0';
    printf("%s",niz);
    return 0;
}

Upvotes: 1

Views: 51

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

calloc() will return 0 filled memory. So, in your case, if none of the if checks match (Which happens in case of randbroj == 10), the niz[i] will not get any new value and hold the default 0 value, which is the value for the null-terminator.

Your string ends there.

Solution: Add the check for all possible values, including 10.

Upvotes: 3

Related Questions