C Nested Structure

A nested structure means one structure is a member of another structure. For example, a student has an address, and the address has a city and a pincode.

Example

#include <stdio.h>
#include <string.h>

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

struct Student {
    int roll;
    char name[30];
    struct Address addr;     // nested structure
};

int main(void) {
    struct Student s;

    s.roll = 1;
    strcpy(s.name, "Robin");
    strcpy(s.addr.city, "Delhi");
    s.addr.pincode = 110001;

    printf("%d %s\n", s.roll, s.name);
    printf("%s - %d\n", s.addr.city, s.addr.pincode);
    return 0;
}

Output:

Output of the above program is

1 Robin
Delhi – 110001

To reach an inner member, use the dot operator two times: s.addr.city.

Initialize a nested structure

#include <stdio.h>

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

struct Person {
    char name[20];
    struct Date dob;
};

int main(void) {
    struct Person p = {"Maria", {15, 8, 2001}};

    printf("%s was born on %d/%d/%d\n", p.name, p.dob.day, p.dob.month, p.dob.year);
    return 0;
}

Output:

Output of the above program is

Maria was born on 15/8/2001

Note: The inner structure must be defined before the outer one. A structure cannot contain itself, but it can contain a pointer to its own type (used in linked lists).

Next: C Array of Structures.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.