Showing posts with label Nested Structure in C. Show all posts
Showing posts with label Nested Structure in C. Show all posts

Friday, July 6, 2018

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

  1. By separate structure
  2. By Embedded structure

1) 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 Employee
{
int id;
char name[20];
struct Date doj;
}emp1;



As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.

2) 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 structures.





struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;



Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below





e1.doj.dd
e1.doj.mm
e1.doj.yyyy



C Nested Structure example

Let's see a simple example of nested structure in C language.





#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Rama");//copying string into char array
e1.doj.dd=09;
e1.doj.mm=10;
e1.doj.yyyy=2018;

//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}



Output:

employee id : 101

employee name : Rama

employee date of joining (dd/mm/yyyy) : 09/10/2018




Instagram