C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Structure and Union
  5. Nested Structure

Nested Structure

A nested structure in C is a structure that contains another structure as a member. It allows grouping of related data in a hierarchical form, helping to represent complex entities logically.

Thank you for reading this post, don't forget to subscribe!
  • This concept is especially useful when one structure is a logical part of another.
  • For example, a Date structure can be nested within an Employee structure to store the employee’s date of birth.

Why Use Nested Structures?

  • To represent real-world complex objects more accurately.
  • To keep the code modular and readable.
  • To reuse smaller structures inside larger ones.

Syntax of Nested Structure:

struct Inner {
    data_type member1;
    data_type member2;
};

struct Outer {
    data_type outer_member;
    struct Inner inner_object; // Nested structure
};

Example: Nested Structure in C:

#include <stdio.h>

// Define inner structure
struct Date {
    int day;
    int month;
    int year;
};

// Define outer structure
struct Employee {
    int id;
    char name[50];
    struct Date dob; // Nested structure
};

int main() {
    struct Employee emp1;

    // Assign values
    emp1.id = 101;
    strcpy(emp1.name, "Alice");
    emp1.dob.day = 15;
    emp1.dob.month = 8;
    emp1.dob.year = 1995;

    // Display data
    printf("Employee ID: %d\n", emp1.id);
    printf("Employee Name: %s\n", emp1.name);
    printf("Date of Birth: %02d-%02d-%d\n", 
           emp1.dob.day, emp1.dob.month, emp1.dob.year);

    return 0;
}

Output:

Employee ID: 101
Employee Name: Alice
Date of Birth: 15-08-1995

How can we help?