Wednesday, 15 April 2020

Nested structures in C


When a structure contains another structure as its member, it is called a nested structure.
Syntax:
  struct innerStruct{
     -------------------
     -------------------
};

struct outerStruct{
     -------------------
     -------------------
   struct innerStruct inner;
};

For example, we want to store information about an employee-empName, empNo, dept,address. Address can be broken into houseNo,city,pincode so we will store address details in another structure named Address and other information about employee in Employee structure.
#include<stdio.h>
//Inner structure
struct Address{
  char houseNo[20];
  char city[20];
};

//Outer structure
struct Employee{
  char empName[25];
  char  dept[15];
  struct Address add;
};

int main(){
  struct Employee emp;
  printf("Enter Employee Name: ");
  scanf("%s",&emp.empName);
  printf("Enter Employee Department: ");
  scanf("%s",&emp.dept);

  printf("Enter Employee Address details:\n ");
  printf("Enter Employee House No: ");
  scanf("%s",&emp.add.houseNo);
  printf("Enter Employee City: ");
  scanf("%s",&emp.add.city);

  printf("\nEmployee Details\n");
  printf("Name :%s\n",&emp.empName);
  printf("Department :%s\n",&emp.dept);
  printf("House No :%s\n",&emp.add.houseNo);
  printf("City :%s\n",&emp.add.city);
  return 0;
}

Output:


Note that inner structure must be declared before outer structure.

You may also like:

 Structure in C
 Typedef in C with examples
 Array of Structures in C with Example
 Self Referential Structures in C
 Passing structure to a function in C with example

Please comment and share if you find it useful.


No comments:

Post a Comment