The structures are data types that are especially useful for creating collection items. We can make a collection of them using an array. Similarly, we can create array of Unions.
Consider a case, where we need to store the data of 5 students. We can store it by using the structure as given below.
#includestruct student { char name[20]; int id; float marks; }; void main() { struct student s1,s2,s3; int dummy; printf("Enter the name, id, and marks of student 1 "); scanf("%s %d %f",s1.name,&s1.id,&s1.marks); scanf("%c",&dummy); printf("Enter the name, id, and marks of student 2 "); scanf("%s %d %f",s2.name,&s2.id,&s2.marks); scanf("%c",&dummy); printf("Enter the name, id, and marks of student 3 "); scanf("%s %d %f",s3.name,&s3.id,&s3.marks); scanf("%c",&dummy); printf("Printing the details....\n"); printf("%s %d %f\n",s1.name,s1.id,s1.marks); printf("%s %d %f\n",s2.name,s2.id,s2.marks); printf("%s %d %f\n",s3.name,s3.id,s3.marks); }
In the above program, we have stored data of 3 students in the structure. The complexity of the program will be increased if there are more students. If we have 30 student, we will have to declare 30 different structure variables and store them one by one. To avoid declaring the different structure variables, we can make a collection containing all the structures that store the information of different entities.
An array of structures in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. It is also known as the collection of structures.
The following code snippet shows how to create an array of structures and access a particular structure element’s member.
struct student { int rno; char name[50]; } std1[10]; struct student std2[5]; std1[0].rno = 10; std2[4].name = “umar”;
Below is an example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h> #include <string.h> struct student { int rollno; char name[10]; }; int main() { int i; struct student st[5]; printf("Enter Records of 5 students"); for (i = 0; i < 5; i++) { printf("\nEnter Rollno:"); scanf("%d", & amp; st[i].rollno); printf("\nEnter Name:"); scanf("%s", & amp; st[i].name); } printf("\nStudent Information List:"); for (i = 0; i < 5; i++) { printf("\nRollno:%d, Name:%s", st[i].rollno, st[i].name); } return 0; }
The following code snippet shows how to create an array of unions and access a particular union element’s member.
union student { int rno; char name[50]; } std1[10]; union student std2[5]; std1[0].rno = 10; std2[4].name = “umar”;