简体   繁体   English

C:scanf()函数无法正常工作

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

I am having trouble with the scanf() function. 我在使用scanf()函数时遇到麻烦。 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 编号: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 . name为NULL(即,它指向无效的内存位置 ),并将其用作%s的参数会调用未定义的行为

You need to allocate memory to name before you can use that to hold the input. 您需要先分配内存来name然后才能使用它来保存输入。

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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