0
0
Cprogramming~5 mins

Nested structures

Choose your learning style9 modes available
Introduction

Nested structures let you put one structure inside another. This helps organize related data clearly.

When you want to group related information inside a bigger group, like an address inside a person.
When you need to keep data organized in layers, like a date inside an event.
When you want to reuse smaller structures inside bigger ones to avoid repeating code.
Syntax
C
struct Inner {
    int value;
};

struct Outer {
    struct Inner innerData;
    int otherValue;
};
You define one structure inside another by declaring it as a member.
Access nested members using dot notation: outer.innerData.value
Examples
This example shows an Event structure that contains a Date structure inside it.
C
struct Date {
    int day;
    int month;
    int year;
};

struct Event {
    char name[50];
    struct Date eventDate;
};
Here, Rectangle has two Point structures nested inside to represent corners.
C
struct Point {
    int x;
    int y;
};

struct Rectangle {
    struct Point topLeft;
    struct Point bottomRight;
};
Sample Program

This program creates an Event with a nested Date. It prints the event name and date clearly.

C
#include <stdio.h>

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

struct Event {
    char name[50];
    struct Date eventDate;
};

int main() {
    struct Event meeting = {"Team Meeting", {15, 6, 2024}};

    printf("Event: %s\n", meeting.name);
    printf("Date: %d/%d/%d\n", meeting.eventDate.day, meeting.eventDate.month, meeting.eventDate.year);

    return 0;
}
OutputSuccess
Important Notes

Remember to use the dot operator to access nested structure members.

You can nest structures multiple levels deep if needed.

Summary

Nested structures help organize complex data by putting one structure inside another.

Use dot notation to access inner members.

This keeps your code clean and easy to understand.