Nested Structure in C

By | February 20, 2023

In C programming language, a structure is a composite data type that groups together variables of different data types under a single name. A nested structure is a structure that has another structure as one of its members.

Example:
Here’s an example of a nested structure in C:

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

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

struct student {
    char name[50];
    int roll_number;
    struct date date_of_birth;
};

int main() {
    struct student s1;

    strcpy(s1.name, "John Smith");
    s1.roll_number = 101;
    s1.date_of_birth.day = 15;
    s1.date_of_birth.month = 8;
    s1.date_of_birth.year = 1995;

    printf("Name: %s\n", s1.name);
    printf("Roll number: %d\n", s1.roll_number);
    printf("Date of birth: %d/%d/%d\n", s1.date_of_birth.day, s1.date_of_birth.month, s1.date_of_birth.year);

    return 0;
}

In this example, we define two structures: date and student. The date structure has three members: day, month, and year, all of type int. The student structure has three members: name, of type char array, roll_number, of type int, and date_of_birth, of type date.

We then declare a variable s1 of type student, and initialize its members using dot notation. Finally, we print the values of the structure members using printf statements.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.