Like any other variable, a structure variable can also be initialized where they are declared. There is a one-to-one relationship between the members and their initializing values. To access the members, we have to use ” . “(the dot operator).
Don’t know what is structure type data in C? Read: Structure datatype in C
Example
Example
/* C program to understand the initializing and accessing the members of structure type data */
#include <stdio.h>
typedef struct {
char name[20];
int roll;
char gender;
int marks[5];
} STUDENT; // Declaration of a structure named “STUDENT”
int main() {
STUDENT st1 = { “Rohan”, 40, ‘M’, {79, 89, 86, 78, 72}}; // Initializing “st1” by some values
STUDENT st2 = { “Ronaldo”, 07, ‘M’, {97, 88, 92, 86, 98}}; // Initializing “st2” by some values
/* Printing the details of 1st student */
printf (“Details of 1st student: \n”);
printf (“Name: %s\n”, st1.name);
printf (“Roll: %d\n”, st1.roll);
printf (“Gender: %c\n”, st1.gender);
for (int i = 0; i < 5; ++i)
printf (“Marks in subject – %d: %d\n”, i+1, st1.marks[i]);
/* Printing the details of 2nd student */
printf (“Details of 2nd student: \n”);
printf (“\nName: %s\n”, st2.name);
printf (“Roll: %d\n”, st2.roll);
printf (“Gender: %c\n”, st2.gender);
for (int i = 0; i < 5; ++i)
printf (“Marks in subject – %d: %d\n”, i+1, st2.marks[i]);
return 0;
}
Output:
Details of 1st student:
Name: Rohan
Roll: 40
Gender: M
Marks in subject – 1 is: 79
Marks in subject – 2 is: 89
Marks in subject – 3 is: 86
Marks in subject – 4 is: 78
Marks in subject – 5 is: 72
Details of 2nd student:
Name: Ronaldo
Roll: 07
Gender: M
Marks in subject – 1 is: 97
Marks in subject – 2 is: 88
Marks in subject – 3 is: 92
Marks in subject – 4 is: 86
Marks in subject – 5 is: 98
In the above example the members can also be initialized in the variable declaration in any order using the ” . ” operator. Let us consider another structure (STUDENT) type data as st3 here.
Example
Example