Wednesday, July 6, 2022

[FIXED] Why dereference a reference in C? Using & next to *

Issue

I looked at this and this and this and this and more.

Question is:

A basic C Programming MOOC on EdX is showing how to access a member of a struct within a function, when the struct was passed by pointer. Why in the world are they using & next to *???

They show: scanf("%lf", &(*studptr).aveGrade);

Why not just use studptr.aveGrade in scanf?

(Leaving aside the separate question, "why use scanf at all")

(Was asked for complete example)

void readStudent(struct student *studptr) {
    print("\nEnter a new student record: \n");
    printf("First name: ");
    scanf("%s", (*studptr).firstName);
    printf("Last name: ");
    scanf("%s", (*studptr).lastName);
    printf("Birth year: ");
    scanf("%d", &(*studptr).birthYear);
    printf("Average grade: ");
    scanf("%lf", &(*studptr).aveGrade);
}

Solution

Because & doesn't refer to (*stupdtr), it refers to (*studptr).aveGrade. The . operator has higher precedence.



Answered By - Federico klez Culloca
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.