C nested structure
Contents
Structure within Structure : Nested Structure
- Structure written inside another structure is called as nesting of two structures.
- Nested Structures are allowed in C Programming Language.
- We can write one Structure inside another structure as member of another structure.
Way 1 : Declare two separate structures
struct date { int date; int month; int year; }; struct Employee { char ename[20]; int ssn; float salary; struct date doj; }emp1;
Accessing Nested Elements :
- Structure members are accessed using dot operator.
- ‘date‘ structure is nested within Employee Structure.
- Members of the ‘date‘ can be accessed using ‘employee’
- emp1 & doj are two structure names (Variables)
Explanation Of Nested Structure :
Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year Field : emp1.doj.year
Way 2 : Declare Embedded structures
struct Employee { char ename[20]; int ssn; float salary; struct date { int date; int month; int year; }doj; }emp1;
Accessing Nested Members :
Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year Field : emp1.doj.year
Live Complete Example :
#include <stdio.h> struct Employee { char ename[20]; int ssn; float salary; struct date { int date; int month; int year; }doj; }emp = {"Pritesh",1000,1000.50,{22,6,1990}}; int main(int argc, char *argv[]) { printf("\nEmployee Name : %s",emp.ename); printf("\nEmployee SSN : %d",emp.ssn); printf("\nEmployee Salary : %f",emp.salary); printf("\nEmployee DOJ : %d/%d/%d", \ emp.doj.date,emp.doj.month,emp.doj.year); return 0; }
Output :
Employee Name : Pritesh Employee SSN : 1000 Employee Salary : 1000.500000 Employee DOJ : 22/6/1990