In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure.
- By separate structure
- By Embedded structure
- Separate structure
In a separate structure, we can create one or more structure inside the main structure as a member.
Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 |
strcut Dob{ int date; char month[20]; int year; } struct student{ int id; char nm[30]; struct Dob doj; }std1; |
- Embedded structure:
The embedded structure can be created within the structure. Let us consider how to declare the embedded structure.
Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
struct student { int id; char name[20]; struct Dob { int data; char month[20]; int year; }doj; }std1; |
Example
Write a program of Nested structure in C language.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <stdio.h> struct student{ int id; char ename[20]; struct date { int date; int month; int year; }doj; } std = {101,"Mohan",{22,6,1990}}; int main(int argc, char *argv[]){ printf("\nEmployee SSN : %d",std.id); printf("\nEmployee Name : %s",std.ename); printf("\nEmployee DOJ :%d/%d/%d",std.doj.date,std.doj.month,std.doj.year); return 0; } |
Output
1 2 3 4 5 |
Employee SSN : 101 Employee Name : Mohan Employee DOJ :22/6/1990 |