Skip to content
StudyFame

Nested Structures in C

A student record needs a date of birth. A date itself has three parts: day, month and year. Instead of adding three loose members, you can make a date structure and put it inside the student structure.

This is a nested structure. In this lesson you will create nested structures in two ways, access deep members like s.dob.year, and build an employee record with a date and an address.

What You Will Learn

  • What a nested structure is.
  • Two ways to nest: separate and embedded.
  • How to access members with more than one dot.
  • How to initialize a nested structure.
  • How to use nested structures in an array.

What is a Nested Structure in C?

Exam definition: A nested structure is a structure that has another structure as one of its members. Inner members are accessed by chaining the dot operator, e.g. outer.inner.member.

Memory trick: Nested structures are like a postal address: Country → State → City. To reach the city, you go through each level: india.up.lucknow. In C: student.dob.year, read as "student's dob's year".

Syntax: Two Ways to Nest a Structure

/* Way 1: separate structure (reusable, recommended) */
struct date
{
    int day, month, year;
};

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

/* Way 2: embedded structure (used only inside student) */
struct employee
{
    int id;
    struct
    {
        char city[20];
        int pin;
    } address;                  /* member name of the inner struct */
};

struct student s = {101, "Asha", {15, 8, 2005}};   /* inner braces */
s.dob.year = 2006;                                  /* chain the dots */
WayInner type reusable?Use when
Separate (struct date defined first)Yes: any structure can use struct dateThe inner data appears in many places (dates, addresses)
Embedded (defined inside)NoThe inner data belongs to just one structure

With the separate way, the inner structure must be defined before the outer one uses it.

Example 1: Student with a Date of Birth

#include <stdio.h>

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

struct student
{
    int roll;
    char name[20];
    struct date dob;
    struct date admission;      /* same inner type reused */
};

int main(void)
{
    struct student s = {101, "Asha", {15, 8, 2005}, {1, 7, 2023}};

    printf("Name      : %s\n", s.name);
    printf("Born      : %02d-%02d-%d\n", s.dob.day, s.dob.month, s.dob.year);
    printf("Admitted  : %02d-%02d-%d\n",
           s.admission.day, s.admission.month, s.admission.year);
    printf("Age at admission: about %d years\n", s.admission.year - s.dob.year);

    s.dob.day = 16;             /* change one inner member */
    printf("Corrected : %02d-%02d-%d\n", s.dob.day, s.dob.month, s.dob.year);

    return 0;
}

Output

Name      : Asha
Born      : 15-08-2005
Admitted  : 01-07-2023
Age at admission: about 18 years
Corrected : 16-08-2005

Code Explanation

  1. struct date is defined first, then used twice inside struct student: for dob and admission.
  2. The initializer has inner braces for each date: {15, 8, 2005}.
  3. s.dob.day reads left to right: s → its dob → its day. Each dot goes one level deeper.
  4. %02d prints at least 2 digits with a leading zero, so 1 becomes 01.

How Nested Structures are Stored

The inner structure is stored inside the outer one, as one block. It's not a separate variable somewhere else.

struct student s:
+------+----------------+---------------------------+
| roll |     name       |  dob: [day][month][year]  |
+------+----------------+---------------------------+
                         ^ s.dob is a whole struct date
sizeof(struct student) = sizeof(int) + 20 + sizeof(struct date) (+ any padding)

Because s.dob is a full struct date, you can copy it at once: struct date d = s.dob;.

Example 2: Employee Records with Address and Joining Date

#include <stdio.h>

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

struct employee
{
    int id;
    char name[20];
    struct date joined;
    struct                      /* embedded: used only here */
    {
        char city[15];
        int pin;
    } address;
};

int main(void)
{
    struct employee e[3] = {
        {1, "Kiran", {10, 6, 2015}, {"Pune", 411001}},
        {2, "Sameer", {3, 1, 2019}, {"Indore", 452001}},
        {3, "Pooja", {21, 9, 2012}, {"Pune", 411014}}
    };
    int i, current_year = 2025;

    printf("%-3s %-7s %-7s %-6s %s\n", "ID", "Name", "City", "PIN", "Years");
    for (i = 0; i < 3; i++)
    {
        printf("%-3d %-7s %-7s %-6d %d\n", e[i].id, e[i].name,
               e[i].address.city, e[i].address.pin,
               current_year - e[i].joined.year);
    }

    printf("Employees in Pune:");
    for (i = 0; i < 3; i++)
        if (e[i].address.pin / 1000 == 411)       /* Pune PINs start with 411 */
            printf(" %s", e[i].name);
    printf("\n");

    return 0;
}

Output

ID  Name    City    PIN    Years
1   Kiran   Pune    411001 10
2   Sameer  Indore  452001 6
3   Pooja   Pune    411014 13
Employees in Pune: Kiran Pooja
  • e[i].address.city: index the array, then go two levels in.
  • The embedded struct has no tag, so it can't be used anywhere else. That's fine for data that only employees have.
  • joined reuses struct date, the same type a student or invoice could use.

Important Points to Remember

  • A nested structure has a structure as a member.
  • Access with chained dots: s.dob.year.
  • Define the inner structure before the outer (separate way).
  • Initialize with inner braces: {101, "Asha", {15, 8, 2005}}.
  • The inner struct is stored inside the outer struct's memory.
  • A structure cannot contain itself (but can contain a pointer to itself, used in linked lists).

Common Mistakes Beginners Make

MistakeWhat happensFix
s.year instead of s.dob.yearError: no member named yearGo through every level
Using struct date before defining itError: incomplete typeDefine the inner struct first
Forgetting inner braces in initializationValues shift into wrong members (warnings)Wrap each inner struct in {}
struct node { int x; struct node next; };Error: struct contains itselfUse struct node *next;
Embedded struct without a member nameCan't access its fields (in older C)Give it a name, like address

Nested Structures Practice Questions

  1. Define a nested structure.
  2. Write the expression for the month of joining of employee e[2] from Example 2.
  3. What is the difference between separate and embedded nesting?
  4. Can a structure contain a variable of its own type? What about a pointer to its own type?
  5. Initialize struct student s (roll, name, dob) for roll 7, "Om", born 5-1-2004.
Show answers
  1. A structure that has another structure as one of its members.
  2. e[2].joined.month
  3. Separate: the inner type is defined on its own and can be reused. Embedded: defined inside the outer struct and used only there.
  4. No (it would be infinitely large). Yes, a pointer to its own type is allowed (self-referential structure).
  5. struct student s = {7, "Om", {5, 1, 2004}};

Coding Exercise

Create struct time {int h, m;} and struct train {char name[20]; struct time dep, arr;}. For the train "Shatabdi" departing 06:15 and arriving 11:50, print the journey time in hours and minutes.

Show solution
#include <stdio.h>

struct time { int h, m; };
struct train { char name[20]; struct time dep, arr; };

int main(void)
{
    struct train t = {"Shatabdi", {6, 15}, {11, 50}};
    int start = t.dep.h * 60 + t.dep.m;
    int end = t.arr.h * 60 + t.arr.m;
    int mins = end - start;

    printf("%s: %d h %d min\n", t.name, mins / 60, mins % 60);
    return 0;
}
Shatabdi: 5 h 35 min

Quick Quiz: Nested Structures (MCQ)

  1. To access year inside dob inside s:

    A) s.year   B) s.dob.year   C) s->dob->year   D) dob.s.year

  2. In the separate way, the inner structure must be:

    A) Defined after the outer   B) Defined before the outer   C) A pointer   D) A union

  3. Which is invalid?

    A) struct a { int x; struct a *p; };   B) struct a { int x; struct a y; };   C) struct b { struct date d; };   D) None

  4. An embedded structure without a tag can be used:

    A) Anywhere   B) Only inside the outer structure   C) Only in main   D) Never

  5. struct date d = s.dob; is:

    A) An error   B) A valid copy of the whole inner structure   C) A pointer   D) A comparison

Show answers
  1. B: s.dob.year.
  2. B: defined before.
  3. B: a structure can't contain itself.
  4. B: only inside the outer structure.
  5. B: a valid copy.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Nested structureStructure inside a structure
Accessouter.inner.member
Separate wayInner defined first, reusable
Embedded wayDefined inside, used only there
InitializeInner braces: {1, "A", {5, 1, 2004}}
Self-containingNot allowed; pointer to self is allowed

Frequently asked questions

What is a nested structure?
A structure that has another structure as a member, accessed with chained dots.
Can a structure contain itself?
No, its size would be infinite. It can contain a pointer to itself (self-referential structure).
Why use nested structures?
To organize related data (date, address) and reuse the same inner type in many records.

Remember

  • Nested = postal address: country → state → city.
  • One dot per level.

Next Topic

Next lesson: Structures and Pointers in C. You will use pointers to structures and the arrow operator (->).