Skip to main content

Nested structures with example

Short answer

Nested structures contain another structure as a member, useful for hierarchical data like a date inside a student record. Define the inner structure first, then declare it in the outer; access members with dot operators, e.g., s.dob.month.

What do you mean by nested structures? Explain nested structure with suitable example. (Need of nested structure; how can we create and use a structure within another.)

Meaning

A nested structure is a structure that has another structure as one of its members. The inner structure must be defined before it is used in the outer structure.

Need

  • Real-world data is often hierarchical: a student has a date of birth, which itself has day, month and year; an employee has an address.
  • It groups related data, reuses one structure (such as date) in many places, and keeps the program readable.

Creating a nested structure

struct date { int day, month, year; };

struct student {
    char name[30];
    int roll;
    struct date dob;       /* structure inside structure */
};

(The inner structure can also be defined inside the outer one.)

Using it

Members are reached by repeating the dot operator from the outside in: s.dob.month. It can be initialised with nested braces: {"Sita", 12, {5, 8, 2005}}.

#include <stdio.h>

struct date {
    int day, month, year;
};

struct student {
    char name[30];
    int roll;
    struct date dob;          /* nested structure */
};

int main(void)
{
    struct student s = {"Sita", 12, {5, 8, 2005}};

    printf("Name: %s, Roll: %d\n", s.name, s.roll);
    printf("DOB : %d/%d/%d\n", s.dob.day, s.dob.month, s.dob.year);
    return 0;
}

Output:

Name: Sita, Roll: 12
DOB : 5/8/2005

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 8 questions →