Accessing the members of a structure

Individual structure members can be used like other variables of the same type. Structure members are accessed using the structure member operator (.), also called the dot operator, between the structure name and the member name. The syntax for accessing the member of the structure is:

structurevariable. member-name;

Let us take the example of the coordinate structure.

struct coordinate
{
int x;
int y;
};

Thus, to have the structure named first refer to a screen location that has coordinates x=50, y=100, you could write as,

first.x = 50;
first.y = 100;

To display the screen locations stored in the structure second, you could write,

printf (“%d,%d”, second.x, second.y);

The individual members of the structure behave like ordinary date elements and can be accessed accordingly.

Now let us see the following program to clarify our concepts. For example, let us see, how will we go about storing and retrieving values of the individual data members of the student structure.

Program to store and retrieve the values from the student structure
#include<stdio.h>
struct student {
int roll_no;
char name[20];
char course[20];
int marks_obtained ;
};
main()
{
student s1 ;
printf (“Enter the student roll number:”);
scanf (“%d”,&s1.roll_no);
printf (“\nEnter the student name: “);
scanf (“%s”,s1.name);
printf (“\nEnter the student course”);
scanf (“%s”,s1.course);
printf (“Enter the student percentage\n”);
scanf (“%d”,&s1.marks_obtained);
printf (“\nData entry is complete”);
printf ( “\nThe data entered is as follows:\n”);
printf (“\nThe student roll no is %d”,s1.roll_no);
printf (“\nThe student name is %s”,s1.name);
printf (“\nThe student course is %s”,s1.course);
printf (“\nThe student percentage is %d”,s1.marks_obtained);
}

OUTPUT

Enter the student roll number: 1234
Enter the student name: ARUN
Enter the student course: MCA
Enter the student percentage: 84
Date entry is complete
The data entered is as follows:
The student roll no is 1234
The student name is ARUN
The student course is MCA
The student percentage is 84

Another way of accessing the storing the values in the members of a structure is by initializing them to some values at the time when we create an instance of the data type.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: