Skip to content
Home » How to use -> operator in struct to calculate average instead of dot( . ) operator.

How to use -> operator in struct to calculate average instead of dot( . ) operator.

Learn about C Program to use -> operator in struct to calculate average instead of dot( . ) operator in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

C Program to use -> operator in struct to calculate average instead of dot( . ) operator:

For using arrow operator in structure ,A pointer must be defined to the structure .For example, let us consider to calculate the average of marks of students defined in structure and to show results of average as output mainly using arrow operator to access members of a structure instead of dot operator.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
    char name[20];
    int maths_marks;
    int phy_marks;
    int che_marks;
    float average;
}*s[10];// s is pointer to the structure student

int main()
{
    int i,n;
    printf("Enter no of students:");
    scanf("%d",&n);

    //Inserting values to the structure
    for(i=0;i<n;i++)
    {
        s[i]=(struct student*)malloc(sizeof(struct student));//dynamically allocating memory
        printf("Enter details of th student no %d\n",i+1);
        printf("Enter name of Student:");
        scanf("%s",s[i]->name);
        printf("Enter maths marks:");
        scanf("%d",&s[i]->maths_marks);
        printf("Enter physics marks:");
        scanf("%d",&s[i]->phy_marks);
        printf("Enter chemistry marks:");
        scanf("%d",&s[i]->che_marks);
    }

    //calculating Average of each student
    for(i=0;i<n;i++)
    {
        s[i]->average=(float)(s[i]->maths_marks+s[i]->phy_marks+s[i]->che_marks)/3;
    }
    for(i=0;i<n;i++)
    {
        printf("The average marks of %s is %.2f\n",s[i]->name,s[i]->average);
    }
    return 0;
}

Enter no of students:3
Enter details of th student no 1
Enter name of Student:Shinchan
Enter maths marks:98
Enter physics marks:90
Enter chemistry marks:95
Enter details of th student no 2
Enter name of Student:Nobitha
Enter maths marks:89
Enter physics marks:87
Enter chemistry marks:76
Enter details of th student no 3
Enter name of Student:Oswald
Enter maths marks:95
Enter physics marks:87
Enter chemistry marks:90
The average marks of Shinchan is 94.33
The average marks of Nobitha is 84.00
The average marks of Oswald is 90.67

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.