Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading