简体   繁体   English

使用指针将值分配给结构时出错

[英]Error while assigning values to a struct using pointers

I am new to C and have been trying to get this simple code run which makes use of pointers to struct for calculating the average of grades entered. 我是C语言的新手,并且一直在尝试运行此简单的代码,该代码利用指针的结构来计算输入的平均成绩。 After entering the maths grade, the program throws an error and stops. 进入数学等级后,程序将引发错误并停止。 What am I doing wrong. 我究竟做错了什么。 Its also my first post in here, so please bear with me for any inconsistencies. 这也是我在这里的第一篇文章,因此如有任何不一致之处,请多包涵。 Thanks! 谢谢!

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

typedef struct
{
    char *name;
    int mathGrade,scienceGrade,historyGrade,englishGrade;
}reportCard;

void average(reportCard *rc)
{
    int avg = (rc->mathGrade +rc->scienceGrade+rc->historyGrade+rc->englishGrade)/4;
    printf("The overall grade of %s is: %i ",rc->name, avg);
}

int main()
{
    reportCard rc;
    printf("Enter the Students Last name: ");
    char studentName[20];
    scanf("%s", studentName);

    rc.name=studentName;

    printf("Math Grade: \n");
    scanf("%i", rc.mathGrade);

    printf("Science Grade: \n");
    scanf("%i", rc.scienceGrade);

    printf("History Grade: \n");
    scanf("%i", rc.historyGrade);

    printf("English Grade: \n");
    scanf("%i", rc.englishGrade);

    average(&rc);

    return 0;
}

You get an error because reading primitives with scanf requires pointers: 您会收到错误消息,因为使用scanf读取基元需要指针:

scanf("%i", &rc.mathGrade);
scanf("%i", &rc.scienceGrade);
//          ^
//          |
//        Here
// ...and so on

scanf thinks that an uninitialized int that you pass is a pointer, and tries to write it, which results in an error. scanf认为您传递的未初始化的int是指针,并尝试将其写入,这将导致错误。

In addition, you need to protect against buffer overruns on reading strings, like this: 另外,您需要防止读取字符串时缓冲区溢出,如下所示:

scanf("%19s", studentName); // you allocated 20 chars; you need one for null terminator

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

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