Nested Strucutre in C
×


Nested Strucutre in C

211

 Nested structures in C allow you to define structures within structures, enabling hierarchical data representation.

 This approach is useful for modeling complex entities with multiple layers of attributes.

 Nested structures involve defining a structure inside another structure.

 This creates a hierarchical relationship where the inner structure represents a component or attribute of the outer structure.

 Each structure can have its own set of members, including other structures.

Syntax of Nested Structure in C 

struct Outer {
    // Outer structure members
    struct Inner {
        // Inner structure members
    } inner; // Inner structure variable
};
Example:

#include<stdio.h>

// Define an inner structure
struct Inner {
    int inner_member1;
    float inner_member2;
};

struct Outer {
    int outer_member1;
    struct Inner inner;
};

int main() {
    // Declare variables of the outer structure
    struct Outer outer1, outer2;

    // Initialize members of the outer structure
    outer1.outer_member1 = 10;
    outer1.inner.inner_member1 = 20;
    outer1.inner.inner_member2 = 3.14;

    outer2.outer_member1 = 5;
    outer2.inner.inner_member1 = 15;
    outer2.inner.inner_member2 = 2.71;

    // Display the values
    printf("Outer 1: %d, %d, %.2f\n", outer1.outer_member1, outer1.inner.inner_member1, outer1.inner.inner_member2);
    printf("Outer 2: %d, %d, %.2f\n", outer2.outer_member1, outer2.inner.inner_member1, outer2.inner.inner_member2);

    return 0;
}

Output:

Outer 1: 10, 20, 3.14
Outer 2: 5, 15, 2.71

Uses of Nested Structure in C

 Hierarchical Data Modeling: Representing complex entities with multiple layers of attributes.

 Code Organization: Grouping related data together for better code organization and readability.

 Data Abstraction: Abstracting complex data structures into manageable components for easier manipulation.

 Object-Oriented Design: Mimicking object-oriented concepts like encapsulation and composition in procedural programming.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments