Nested Structures in C

A Nested Structure means having one structure inside another structure. This helps model complex real-life data like students with address, employees with salary details, etc.

Why Use Nested Structures?

Syntax of Nested Structure

struct Outer {
    int id;

    struct Inner {
        int x;
        int y;
    } point;
};

Accessing Nested Structure Members

Nested Structures — 5 Full Examples

1. Student Structure With Address

#include <stdio.h>

struct Address {
    char city[20];
    int pincode;
};

struct Student {
    int roll;
    struct Address addr;
};

int main(){
    struct Student s = {101, {"Bhubaneswar", 751002}};
    printf("%d %s %d", s.roll, s.addr.city, s.addr.pincode);
    return 0;
}

2. Employee With Salary Breakdown

#include <stdio.h>

struct Salary {
    int basic;
    int hra;
};

struct Employee {
    int id;
    struct Salary sal;
};

int main(){
    struct Employee e = {1, {30000, 5000}};
    printf("%d %d %d", e.id, e.sal.basic, e.sal.hra);
    return 0;
}

3. Product With Manufacturing Date

#include <stdio.h>

struct Date {
    int d, m, y;
};

struct Product {
    int code;
    struct Date mfg;
};

int main(){
    struct Product p = {1001, {12, 5, 2024}};
    printf("%d %d-%d-%d", p.code, p.mfg.d, p.mfg.m, p.mfg.y);
    return 0;
}

4. Vehicle With Engine Details

#include <stdio.h>

struct Engine {
    int cc;
    int power;
};

struct Vehicle {
    char model[20];
    struct Engine eng;
};

int main(){
    struct Vehicle v = {"Swift", {1200, 90}};
    printf("%s %d %d", v.model, v.eng.cc, v.eng.power);
    return 0;
}

5. Book With Author Information

#include <stdio.h>

struct Author {
    char name[20];
    int age;
};

struct Book {
    char title[20];
    struct Author auth;
};

int main(){
    struct Book b = {"C Guide", {"Dennis", 40}};
    printf("%s %s %d", b.title, b.auth.name, b.auth.age);
    return 0;
}

Practice Questions

  1. What is a nested structure? Give its syntax.
  2. How to access members of a nested structure?
  3. Create a structure Employee with nested Address.
  4. Define a structure Book with nested Publisher details.
  5. Explain real-life uses of nested structures.