HOME HTML EDITOR C JAVA PHP

C Nested Structures: Hierarchical Data

**Nested Structures** allow you to organize data into layers. Instead of having a flat list of variables, you can group related attributes into their own small structures and then embed those smaller structures into larger ones. This promotes code reusability and logical organization.

1. How to Define Nested Structures

There are two ways to nest structures: by defining the inner structure outside the main structure, or by defining it inside.

Method A: Separate Definitions (Preferred)

This is the professional standard because it allows you to reuse the inner structure (like Address) in multiple other structures (like Employee or Customer).

struct Date {
    int day;
    int month;
    int year;
};

struct Student {
    char name[50];
    int roll;
    struct Date dob; // Nesting starts here
};

2. Accessing Nested Members

To access the members of a nested structure, you use the Dot Operator (.) twice. You first access the inner structure variable, and then the specific member within it.

struct Student s1;

// Accessing outer and inner members
s1.roll = 101;
s1.dob.day = 15;
s1.dob.month = 8;
s1.dob.year = 2005;

printf("Birth Year: %d", s1.dob.year);

3. Initialization of Nested Structs

When initializing a nested structure in a single line, use nested curly braces { { } } to keep the data organized according to the structure's hierarchy.

struct Student s2 = {"Alice", 102, {15, 8, 2005}};

4. Method B: Embedded Definition

You can also define the inner structure directly inside the outer one. However, this structure cannot be used elsewhere in your program.

struct Employee {
    int id;
    struct Salary {
        float base;
        float bonus;
    } pay;
};

5. Nested Structs with Pointers

If you are using a pointer to the outer structure, you use the Arrow Operator (->) for the first level, but if the inner level is not a pointer, you stick to the dot operator for the nested member.

struct Student *ptr = &s1;
printf("Day: %d", ptr->dob.day);

6. Comparison Table

Feature Flat Structure Nested Structure
Organization Scattered variables. Logical grouping.
Readability Moderate. High (Self-documenting).
Access Level Single dot (s.id). Double dot (s.dob.day).
Pro Tip: Nested structures are heavily used in systems programming (like defining network packets or file system headers). Combining them with typedef makes your code look incredibly clean and professional.