Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
Difference between Struct and Enum in C/C++ with Examples
Next article icon

Nested Structure in C with Examples

Last Updated : 07 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Pre-requisite: Structures in C

A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.

Syntax:

struct name_1
{
    member1;
   member2;
   .
   .
   membern;

   struct name_2
   {
       member_1;
       member_2;
       .
       .
      member_n;
   }, var1
} var2;

The member of a nested structure can be accessed using the following syntax:

Variable name of Outer_Structure.Variable name of Nested_Structure.data member to access 

Example:

  • Consider there are two structures Employee (depended structure) and another structure called Organisation(Outer structure).
  • The structure Organisation has the data members like organisation_name,organisation_number.
  • The Employee structure is nested inside the structure Organisation and it has the data members like employee_id, name, salary.

For accessing the members of Organisation and Employee following syntax will be used:

org.emp.employee_id;
org.emp.name;
org.emp.salary;

org.organisation_name;
org.organisation_number;

Here, org is the structure variable of the outer structure Organisation and emp is the structure variable of the inner structure Employee.

Different ways of nesting structure

The structure can be nested in the following different ways:

  1. By separate nested structure
  2. By embedded nested structure.

1. By separate nested structure: In this method, the two structures are created, but the dependent structure(Employee) should be used inside the main structure(Organisation) as a member. Below is the C program to implement the approach:

C
// C program to implement  // the above approach #include <stdio.h> #include <string.h>  // Declaration of the  // dependent structure struct Employee {   int employee_id;   char name[20];   int salary; };  // Declaration of the  // Outer structure struct Organisation  {   char organisation_name[20];   char org_number[20];      // Dependent structure is used    // as a member inside the main   // structure for implementing    // nested structure   struct Employee emp;  };  // Driver code int main() {   // Structure variable   struct Organisation org;       // Print the size of organisation    // structure   printf("The size of structure organisation : %ld\n",            sizeof(org));      org.emp.employee_id = 101;     strcpy(org.emp.name, "Robert");   org.emp.salary = 400000;   strcpy(org.organisation_name,           "GeeksforGeeks");   strcpy(org.org_number, "GFG123768");         // Printing the details   printf("Organisation Name : %s\n",            org.organisation_name);     printf("Organisation Number : %s\n",            org.org_number);     printf("Employee id : %d\n",            org.emp.employee_id);     printf("Employee name : %s\n",            org.emp.name);     printf("Employee Salary : %d\n",            org.emp.salary);   } 


Output:

The size of structure organisation : 68
Organisation Name : GeeksforGeeks
Organisation Number : GFG123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000

2. By Embedded nested structure: Using this method, allows to declare structure inside a structure and it requires fewer lines of code. 

Case 1: Error will occur if the structure is present but the structure variable is missing.

C
// C program to implement  // the above approach #include <stdio.h>  // Declaration of the outer // structure struct Organisation  {   char organisation_name[20];   char org_number[20];      // Declaration of the employee   // structure   struct Employee    {     int employee_id;     char name[20];     int salary;        // This line will cause error because    // datatype struct Employee is present ,   // but Structure variable is missing.   };  };  // Driver code int main() {   // Structure variable of organisation   struct Organisation org;   printf("%ld", sizeof(org)); } 


Output:

Error


Note:

Whenever an embedded nested structure is created, the variable declaration is compulsory at the end of the inner structure, which acts as a member of the outer structure. It is compulsory that the structure variable is created at the end of the inner structure. 

Case 2: When the structure variable of the inner structure is declared at the end of the inner structure. Below is the C program to implement this approach:

C
// C program to implement // the above approach #include <stdio.h> #include <string.h>  // Declaration of the main // structure struct Organisation  {   char organisation_name[20];   char org_number[20];      // Declaration of the dependent   // structure   struct Employee    {     int employee_id;     char name[20];     int salary;        // variable is created which acts    // as member to Organisation structure.   } emp;  };  // Driver code int main() {   struct Organisation org;      // Print the size of organisation    // structure   printf("The size of structure organisation : %ld\n",            sizeof(org));      org.emp.employee_id = 101;     strcpy(org.emp.name, "Robert");   org.emp.salary = 400000;   strcpy(org.organisation_name,           "GeeksforGeeks");   strcpy(org.org_number, "GFG123768");         // Printing the details   printf("Organisation Name : %s\n",            org.organisation_name);     printf("Organisation Number : %s\n",            org.org_number);     printf("Employee id : %d\n",            org.emp.employee_id);     printf("Employee name : %s\n",            org.emp.name);     printf("Employee Salary : %d\n",            org.emp.salary);   } 


Output:

The size of structure organisation : 68
Organisation Name : GeeksforGeeks
Organisation Number : GFG123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000

Drawback of Nested Structure

The drawback in nested structures are:

  • Independent existence not possible: It is important to note that structure Employee doesn't exist on its own. One can't declare structure variable of type struct Employee anywhere else in the program.
  • Cannot be used in multiple data structures: The nested structure cannot be used in multiple structures due to the limitation of declaring structure variables within the main structure. So, the most recommended way is to use a separate structure and it can be used in multiple data structures


C Nested Structure Example

Below is another example of a C nested structure.

C
// C program to implement  // the nested structure #include <stdio.h> #include <string.h>  // Declaration of Outer structure struct College  {   char college_name[20];   int ranking;      // Declaration of Inner structure   struct Student    {     int student_id;     char name[20];     int roll_no;        // Inner structure variable   } student1; };    // Driver code int main() {   struct College c1 = {"GeeksforGeeks", 7,                       {111, "Paul", 278}};    printf("College name : %s\n",            c1.college_name);   printf("Ranking : %d\n",            c1.ranking);   printf("Student id : %d\n",            c1.student1.student_id);   printf("Student name : %s\n",            c1.student1.name);   printf("Roll no : %d\n",            c1.student1.roll_no);   return 0; } 


Output:

College name : GeeksforGeeks
Ranking : 7
Student id : 111
Student name : Paul
Roll no : 278

Note:

Nesting of structure within itself is not allowed. 

Example:

struct student
{

    char name[50];

    char address[100];

    int roll_no;

    struct student geek; // Invalid

}


Passing nested structure to function

A nested structure can be passed into the function in two ways:

  1. Pass the nested structure variable at once.
  2. Pass the nested structure members as an argument into the function.

Let's discuss each of these ways in detail.

1. Pass the nested structure variable at once: Just like other variables, a nested structure variable can also be passed to the function. Below is the C program to implement this concept:

C
// C program to implement // the above approach #include <stdio.h>  // Declaration of the inner  // structure struct Employee  {   int employee_id;   char name[20];   int salary; };  // Declaration of the Outer  // structure struct Organisation  {   char organisation_name[20];   char org_number[20];      // Nested structure   struct Employee emp;  };  // Function show is expecting  // variable of outer structure void show(struct Organisation);  // Driver code int main() {   struct Organisation org = {"GeeksforGeeks", "GFG111",                             {278, "Paul",5000}};      // Organisation structure variable    // is passed to function show   show(org); }  // Function shoe definition void show(struct Organisation org ) {   // Printing the details   printf("Printing the Details :\n");    printf("Organisation Name : %s\n",            org.organisation_name);     printf("Organisation Number : %s\n",            org.org_number);     printf("Employee id : %d\n",            org.emp.employee_id);     printf("Employee name : %s\n",            org.emp.name);     printf("Employee Salary : %d\n",            org.emp.salary);   }  


Output:

Printing the Details :
Organisation Name : GeeksforGeeks
Organisation Number : GFG111
Employee id : 278
Employee name : Paul
Employee Salary : 5000

2. Pass the nested structure members as arguments into the function: Consider the following example to pass the structure member of the employee to a function display() which is used to display the details of an employee.

C
// C program to implement // the above approach #include <stdio.h>  // Declaration of the inner  // structure struct Employee  {   int employee_id;   char name[20];   int salary; };  // Declaration of the Outer  // structure struct Organisation  {   char organisation_name[20];   char org_number[20];      // Nested structure   struct Employee emp;  };  // Function show is expecting  // members of both structures void show(char organisation_name[],            char org_number[],           int employee_id,            char name[], int salary);  // Driver code int main() {   struct Organisation org = {"GeeksforGeeks", "GFG111",                             {278, "Paul",5000}};      // Data members of both the structures   // are passed to the function show   show(org.organisation_name, org.org_number,        org.emp.employee_id, org.emp.name,        org.emp.salary); }  // Function show definition void show(char organisation_name[],            char org_number[],           int employee_id,            char name[], int salary) {   // Printing the details   printf("Printing the Details :\n");    printf("Organisation Name : %s\n",            organisation_name);     printf("Organisation Number : %s\n",            org_number);     printf("Employee id : %d\n",            employee_id);     printf("Employee name : %s\n",            name);     printf("Employee Salary : %d\n",            salary);   }  


Output:

Printing the Details :
Organisation Name : GeeksforGeeks
Organisation Number : GFG111
Employee id : 278
Employee name : Paul
Employee Salary : 5000

Accessing Nested Structure

Nested Structure can be accessed in two ways:

  1. Using Normal variable.
  2. Using Pointer variable.

Let's discuss each of these methods in detail.

1. Using Normal variable: Outer and inner structure variables are declared as normal variables and the data members of the outer structure are accessed using a single dot(.) and the data members of the inner structure are accessed using the two dots. Below is the C program to implement this concept:

C
// C program to implement // the above approach #include <stdio.h> #include <string.h>  // Declaration of inner structure struct college_details {   int college_id;   char college_name[50];    };  // Declaration of Outer structure struct student_detail {   int student_id;   char student_name[20];   float cgpa;      // Inner structure variable   struct college_details clg; } stu;  // Driver code int main() {   struct student_detail stu = {12, "Kathy", 7.8,                                {14567, "GeeksforGeeks"}};      // Printing the details   printf("College ID : %d \n", stu.clg.college_id);   printf("College Name : %s \n", stu.clg.college_name);   printf("Student ID : %d \n", stu.student_id);   printf("Student Name : %s \n", stu.student_name);   printf("Student CGPA : %f \n", stu.cgpa);   return 0; } 


Output:

College ID : 14567  
College Name : GeeksforGeeks  
Student ID : 12  
Student Name : Kathy  
Student CGPA : 7.800000 

2. Using Pointer variable: One normal variable and one pointer variable of the structure are declared to explain the difference between the two. In the case of the pointer variable, a combination of dot(.) and arrow(->) will be used to access the data members. Below is the C program to implement the above approach:

C
// C program to implement // the above approach #include <stdio.h> #include <string.h>  // Declaration of inner structure struct college_details {   int college_id;   char college_name[50];    };  // Declaration of Outer structure struct student_detail {   int student_id;   char student_name[20];   float cgpa;      // Inner structure variable   struct college_details clg; } stu, *stu_ptr;  // Driver code int main() {   struct student_detail stu = {12, "Kathy", 7.8,                                {14567, "GeeksforGeeks"}};      stu_ptr = &stu;      // Printing the details   printf("College ID : %d \n", stu_ptr->clg.college_id);   printf("College Name : %s \n", stu_ptr->clg.college_name);   printf("Student ID : %d \n", stu_ptr->student_id);   printf("Student Name : %s \n", stu_ptr->student_name);   printf("Student CGPA : %f \n", stu_ptr->cgpa);   return 0; } 


Output:

College ID : 14567  
College Name : GeeksforGeeks  
Student ID : 12  
Student Name : Kathy  
Student CGPA : 7.800000 

A nested structure will allow the creation of complex data types according to the requirements of the program.


Next Article
Difference between Struct and Enum in C/C++ with Examples
author
sathiyamoorthics19
Improve
Article Tags :
  • C Language
  • C-Structure & Union

Similar Reads

  • Nested Loops in C with Examples
    A nested loop means a loop statement inside another loop statement. That is why nested loops are also called "loop inside loops". We can define any number of loops inside another loop. 1. Nested for Loop Nested for loop refers to any type of loop that is defined inside a 'for' loop. Below is the equ
    5 min read
  • Read/Write Structure From/to a File in C
    For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data. Writing Structure to a File using fwriteWe can use fw
    3 min read
  • Structure Pointer in C
    A structure pointer is a pointer variable that stores the address of a structure. It allows the programmer to manipulate the structure and its members directly by referencing their memory location rather than passing the structure itself. In this article let's take a look at structure pointer in C.
    3 min read
  • Structure of the C Program
    The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. C program must follow the below-mentioned outline in order to successfully compile and execute. Debugging is easier in a well-structured C program. Section
    5 min read
  • Difference between Struct and Enum in C/C++ with Examples
    Structure in C++ A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. Syntax: struct structureName{ member1; member2; member3; . . . member
    3 min read
  • Array of Structures vs Array within a Structure in C
    Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a StructureA structure is a data type in C that allows a group of related variables to be treated as a single unit instead of s
    5 min read
  • Anonymous Union and Structure in C
    In C, anonymous unions and anonymous structures are the unnamed structures and unions whose members can be directly accessed without creating a variable. These are generally used when the members of the union or structure need to be accessed directly, without using a separate name for the union or s
    3 min read
  • Jagged Array or Array of Arrays in C with Examples
    Prerequisite: Arrays in CJagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}
    3 min read
  • Why does empty Structure has size 1 byte in C++ but 0 byte in C
    A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. The general syntax for creating a structure is as shown below: Syntax- struct structur
    3 min read
  • Difference Between Structure and Union in C
    In C programming, both structures and unions are used to group different types of data under a single name, but they behave in different ways. The main difference lies in how they store data. The below table lists the primary differences between the C structures and unions: Parameter Structure Union
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences