Nested Structures in C Programming Language

Notes:

Nesting of structures in C: Embedded structures in C or Nested structures in C
- If required we can place one structure inside another structure; which is called as nesting of structures. A structure inside another structure is called embedded structure.

There are two different ways in which we can nest structures:
1. Defining a structure and declaring its variables; completely inside another structure

Ex:
struct Student
{
int rollnum;
char *name;
struct Date
{
int day;
int month;
int year;
}dateOfBirth;
};

2. Defining a structure independently and declaring its variables inside another structure

Ex:
struct Date
{
int day;
int month;
int year;
};

struct Student
{
int rollnum;
char *name;
struct Date dateOfBirth;
};

Example Code:

#include <stdio.h>

int main()
{
struct Date
{
int day;
int month;
int year;
};

struct Student
{
int rollnum;
char *name;
struct Date dateOfBirth;
};

struct Student student1 = {10,"Suresh",{1,1,2020}};

printf("student1 rollnum=%d\n",student1.rollnum);
// student1 rollnum=10
printf("student1 name=%s\n",student1.name);
// student1 name=Suresh
printf("student1 dateOfBirth=%d/%d/%d\n",student1.dateOfBirth.day, student1.dateOfBirth.month,student1.dateOfBirth.year);
// student1 dateOfBirth=1/1/2020

student1.dateOfBirth.day = 2;
student1.dateOfBirth.month = 2;
printf("\n");
printf("student1 dateOfBirth=%d/%d/%d\n",student1.dateOfBirth.day, student1.dateOfBirth.month,student1.dateOfBirth.year);
// student1 dateOfBirth=2/2/2020

return 0;
}