jeudi 25 mars 2021

Printing weird characters in C

I´ve implemented a couple of functions to generate random strings,

char *ran_string(int max, int min){  //random string with max length and min length

    int tam=rand()%max,i=0;
    char *str;
    if(tam<min)
        tam=min;
    str=malloc(sizeof(char)*tam);
    for(i=0;i<tam;i++) {
        if(i==0){
            str[0]=(char)((rand() % 26) + 65); //Upercase ascii
        }
        else{
            str[i]=(char)((rand() % 26) + 97);  //Lowercase ascii
        }

    }
    return str;
}
char *var_ran_string(int num, int max, int min){ //generates num random strings
char *a;
a=malloc(sizeof(char)*num*max);
strcat(a,ran_string(max,min));
for(int i=0;i<num-1;i++){
    strcat(a," ");
    strcat(a,ran_string(max,min));
}
return a;

}

I´ve tested it out, and the second time that i call var_ran_string it always prints weird characters like h�1�Dvdfn�2�|��� Zlbhh���. Tried calling the function thousands of times, but the second time seems the only problem.




Aucun commentaire:

Enregistrer un commentaire