PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     ampersand, c, pass-by-reference, pointers, scanf     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing