Wednesday, January 22, 2025
HomeProgrammingNested structure In C

Nested structure In C

In C programming, a nested structure refers to the concept of one structure being defined within another structure. This allows you to model more complex data types by combining simple structures.

Syntax

Here’s a simple example of a nested structure:

#include <stdio.h>

struct Address {
    char street[50];
    char city[50];
    char state[20];
    int zip;
};

struct Person {
    char name[50];
    int age;
    struct Address address; // Nested structure
};

int main() {
    struct Person p1;

    // Assign values to the nested structure fields
    strcpy(p1.name, "John Doe");
    p1.age = 30;
    strcpy(p1.address.street, "123 Elm St");
    strcpy(p1.address.city, "Somewhere");
    strcpy(p1.address.state, "XY");
    p1.address.zip = 12345;

    // Display the values
    printf("Name: %s\n", p1.name);
    printf("Age: %d\n", p1.age);
    printf("Address: %s, %s, %s %d\n", p1.address.street, p1.address.city, p1.address.state, p1.address.zip);

    return 0;
}

Explanation:

  1. struct Address: This is a simple structure that stores information about a person’s address (street, city, state, and zip code).
  2. struct Person: This structure contains basic information about a person, such as their name and age, and includes a field of type struct Address (nested structure) to store the person’s address.
  3. Accessing nested structure: The p1.address.street, p1.address.city, etc., are examples of how you access members of the nested structure.
See also  Split array into chunks - javascript

Key Points:

  • Nested structures allow you to break down complex data models into smaller, manageable parts.
  • You can access nested members using the dot operator.
  • When passing a structure with a nested structure to a function, the entire structure (including the nested one) is passed either by value or by reference.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x