简体   繁体   中英

C: The scanf() function is not working as it should

I am having trouble with the scanf() function. When I compile and run this code

        int ID;
        char* name = NULL;
        char sex;
        float quiz1;
        float quiz2;
        float midscore;
        float finalscore;
        float totalscore;

        printf("please enter the student information.\n");
        printf("ID: ");
        scanf("%i", &ID);
        printf("Name: ");
        scanf(" %s", name);
        printf("Sex: ");
        scanf(" %c", &sex);
        printf("Quiz mark(first semester): ");
        scanf(" %f", &quiz1);
        printf("Quiz mark(second semester): ");
        scanf(" %f", &quiz2);
        printf("Mid-term score: ");
        scanf(" %f", &midscore);
        printf("Final score: ");
        scanf(" %f", &finalscore);
        printf("Total score: ");
        scanf(" %f", &totalscore);

What I get is :

ID: 5
Name: alex
Sex: Quiz mark(first semester): Quiz mark(second semester): Mid-term score: Final score: Total score:

Can someone explain me what's going on?

At the point of

 scanf(" %s", name);

name is NULL (ie, it points to invalid memory location ), and using that as the argument to %s invokes undefined behavior .

You need to allocate memory to name before you can use that to hold the input.

Here is the problem:

char* name = NULL;

You need to assign some memory to the pointer before writing any data. You can either assign some space statically or dynamically:

char name[10];
char *name2;
name2 = malloc(10*sizeof(char));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM