Array of Structures in C
There can be array of structures in C programming to store many information of different data types. The array of structures is also known as collection of structures. see an example of structure with array that stores information of 5 students and prints it.#include <stdio.h> #include <string.h> struct student{ int rollno; char name[20]; }; void main(){ int i; struct student st[4]; printf("Enter Records of 4 students"); for(i=0;i<4;i++){ printf("\nEnter Rollno:"); scanf("%d",&st[i].rollno); printf("\nEnter Name:"); scanf("%s",&st[i].name); } printf("\nStudent Information List:"); for(i=0;i<4;i++){ printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name); } } output: Enter Records of 4 students Enter Rollno: 1 Enter Name: pramesh Enter Rollno: 2 Enter Name: Ranjan Enter Rollno: 3 Enter Name: deepak Enter Rollno: 4 Enter Name: anjali Student Information List: Rollno:1, Name: pramesh Rollno:2, Name: Ranjan Rollno:3, Name: deepak Rollno:4, Name: anjali
Nested Structure in C
Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language. By separate structure By Embedded structure
Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.struct Date { int dd; int mm; int yyyy; }; struct student { int id; char name[30]; struct Date doj; }stu1;
Embedded structure
We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structuresstruct Student { int id; char name[30]; struct Date { int dd; int mm; int yyyy; } doj; } stu1;
Accessing Nested Structure
We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:s1.doj.dd s1.doj.mm s1.doj.yyyy
Nested Structure example
see a simple example of nested structure in C language.#include <stdio.h> #include <string.h> struct Student { int id; char name[30]; struct Date { int dd; int mm; int yyyy; } doj; } s1; int main( ) { //storing student information s1.id=110; strcpy(s1.name, "pramesh gupta"); //copying string into char array s1.doj.dd=10; s1.doj.mm=8; s1.doj.yyyy=2017; //printing first student information printf( "student id : %d\n", s1.id); printf( "student name : %s\n", s1.name); printf( "student date of joining (dd/mm/yyyy) : %d/%d/%d\n", s1.doj.dd,s1.doj.mm,s1.doj.yyyy); return 0; } Output: student id : 110 student name : pramesh gupta student date of joining (dd/mm/yyyy) : 10/8/2017