Declaring and Accessing Structure Elements
DECLARING AND ACCESSING STRUCTURE ELEMENT
Declaration :
struct structure_name {
data_type member1;
data_type member2;
// more members if needed
};
where,
- struct: Keyword used to define a structure.
- structure_name: Name of the structure.
- data_type: Data type of each member variable.
- member1, member2, etc.: Names of the member variables within the structure
ACCESSING STRUCTURE ELEMENT
To access the members of a structure in C, you use the dot (.) operator followed by the member name.
#include <stdio.h>
int main() {
// Define a structure named 'Student'
struct Student {
char name[50];
int age;
float mark;
};
// Declare a variable s of type 'struct Student'
struct Student s;
gets(s.name);
scanf("%d%f",&s.age,&s.mark);
// Accessing and printing the values of 'person1' members
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Mark: %.2f\n", s.mark);
}
- To access the name member of Student, we use s.name.
- To access the age member of Student, we use s.age.
- To access the mark member of Student, we use s.mark.