1

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;
}
G5W
  • 36,531
  • 10
  • 47
  • 80
isaric
  • 195
  • 3
  • 18

1 Answers1

3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261