Home > Net >  using arrow operator to calculate average of 3 members of a structure, need to convert from dot oper
using arrow operator to calculate average of 3 members of a structure, need to convert from dot oper

Time:12-15

i am practicing c, and i just learned how to assign integers and create structures, i came across the arrow operator and i do not know how to apply it, i researched a little and i now know that a->b is the same as (*a).b and that arrow is used for pointers, my question is how do i convert this code to use arrow operator instead, i tried changing the members from int to int * but it still does not work.

#include <stdio.h>
#include <string.h>
struct student {
    char name[10];
    int chem_marks;
    int maths_marks;
    int phy_marks;
};
int main()
{
struct student ahmad;
struct student ali;
struct student abu_abbas;

strcpy (ahmad.name,"ahmad");
ahmad.chem_marks=25;
ahmad.maths_marks=50;
ahmad.phy_marks=90;

strcpy (ali.name,"ali");
ali.chem_marks=29;
ali.maths_marks=90;
ali.phy_marks=13;

strcpy (abu_abbas.name,"abu");
abu_abbas.chem_marks=50;
abu_abbas.maths_marks=12;
abu_abbas.phy_marks=80;

int ahmadavg=(ahmad.chem_marks ahmad.maths_marks ahmad.phy_marks)/3;
int aliavg=(ali.chem_marks ali.maths_marks ali.phy_marks)/3;
int abu_abbasavg=(abu_abbas.chem_marks abu_abbas.maths_marks abu_abbas.phy_marks)/3;


printf("%s  ",ahmad.name);
printf("average:%d\n",ahmadavg);
printf("%s ",ali.name);
printf("average:%d\n",aliavg);
printf("%s ",abu_abbas.name);;
printf("average:%d\n",abu_abbasavg);


}

CodePudding user response:

It's not about the members of the struct being pointers or not, it's about haveing a struct vs. a pointer to a struct.

This small example should make it clear:

#include <stdio.h>

struct Foo
{
  int a;
  int b;
};

int main()
{
  struct Foo f = {1,2};    // f is a structre

  struct Foo* pf;          // pf is a pointer to a struct Foo
                           // it points nowhere

  pf = &f;                 // now pf points to f

  printf("%d %d\n", f.a, f.b);         // direct access to f

  printf("%d %d\n", pf->a, pf->b);     // access via a pointer
  printf("%d %d\n", (*pf).a, (*pf).b); // access via a pointer (same as line above)
}
  • Related