Why my const variable change on execution?

i have a random number generator that should be the same number for all execution, but the number change and is not even of 4 numbers?

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
    srand(1); 
    int const numero=rand() % 7000 + 1000;
    char *caracter;

    while (scanf("%s",&caracter)!=EOF){
        printf("%i\n",numero);
    }
    return 0;
}

I use a .txt with random names and the result is this


masa6144
pupu6144
ogro6144
pelad1oo
pedo0
tucan110
lloron28271
cheso111

as you can see the three first names have a 4 length number and same but after the 3 all become weird, what can be ?

>Solution :

&caracter is the address of the pointer itself. It can be 2(AVR),4 or 8 bytes long. Using pointer as a char array makes no sense at all, but you can store there 1, 3, or 7 chars string.

char *caracter; defines an uninitialized pointer.

You need to allocate the memory for your string.

int main(int argc, char const *argv[])
{
    srand(1); 
    int const numero=rand() % 9000 + 1000;
    char character[100];
    //or char *character = malloc(100);

    while (scanf("%99s",caracter)!=EOF){
        printf("%s",caracter); 
        printf("%i\n",numero);
    }
    return 0;
}

Leave a Reply