jeudi 7 mai 2020

Print function print some strange chars

i'm trying to create a random strings using this function:

static char *rand_string(char *str)
{   
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK";
    int i;

    for ( i = 0; i < 10; i++) 
    {
        int key = rand() % (int) (sizeof charset - 1);
        str[i] = charset[key];
    }
        str[11] = '\0';

    return str;
}

The problem is this: sometimes when i am going to print the pointer, it display some strange char like this: bug As you can see in the first launch the chars in a string are 10, in the second and third launch the chars in a string are 11...

This is my program:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

static char *rand_string(char *str);


int main() 
{

    char *string, //str
         *string_result; //str1


    int dimensione= 15,
        i;

    for(i=0;i<dimensione;i++)
    {
        string_result = rand_string(string);
        printf("%s\n", string_result);

    }
}


static char *rand_string(char *str)
{   
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK";
    int i;

    for ( i = 0; i < 10; i++) 
    {
        int key = rand() % (int) (sizeof charset - 1);
        str[i] = charset[key];
    }
        str[11] = '\0';

    return str;
}

You can view and test my code here --> https://onlinegdb.com/r1yY8DWc8




Aucun commentaire:

Enregistrer un commentaire