2

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. 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;
}

1 Answer 1

1

You get an error because reading primitives with scanf requires pointers:

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.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.