Cover Image for C Nested Structure
90 views

C Nested Structure

You can define nested structures, which are structures that are members of another structure. This allows you to create hierarchical and complex data structures where a structure can contain one or more structures as its members. Nested structures are useful for organizing and representing data that has a hierarchical or composite nature.

Here’s how you can define and use nested structures in C:

#include <stdio.h>

// Define the inner structure
struct Address {
    char street[50];
    char city[50];
    char state[20];
    char postal_code[10];
};

// Define the outer structure containing the inner structure
struct Person {
    char name[50];
    int age;
    struct Address address; // Nested structure as a member
};

int main() {
    // Declare a variable of type 'struct Person'
    struct Person person1;

    // Assign values to the members of the outer and inner structures
    strcpy(person1.name, "John");
    person1.age = 30;
    strcpy(person1.address.street, "123 Main St");
    strcpy(person1.address.city, "Anytown");
    strcpy(person1.address.state, "CA");
    strcpy(person1.address.postal_code, "12345");

    // Access and print the members of the structures
    printf("Name: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    printf("Address:\n");
    printf("  Street: %s\n", person1.address.street);
    printf("  City: %s\n", person1.address.city);
    printf("  State: %s\n", person1.address.state);
    printf("  Postal Code: %s\n", person1.address.postal_code);

    return 0;
}

In this example, we define two structures: struct Address and struct Person. struct Address represents an address with its own members (street, city, state, postal code), and struct Person represents a person with its own members (name, age) and includes an instance of struct Address as a member.

You can access the members of the nested structure using the dot notation, as demonstrated in the main() function.

Nested structures are commonly used when you need to model real-world entities that have a hierarchical structure. They help in organizing and encapsulating data efficiently, making the code more readable and maintainable.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS