Nested structures in c programming with examples - C Programming Tutorial

11/17/2023
All Articles

#Nested_structures #C_Programming

Nested structures in c programming with examples - C Programming Tutorial

Nested structures in c with examples

In C programming, nested structures represent to the concept of defining a structure within another structure.
This allows you to create complex data structures by combining multiple structures.where a structure can contain another structure as a member. This allows you to represent complex data structures with multiple levels of abstraction.  Here's an example to illustrate nested structures :

 

#include <stdio.h>
#include <string.h>
// Outer structure
struct Date {
    int day;
    int month;
    int year;
};

// Inner structure nested inside the Date structure
struct Student {
    char name[50];
    int age;
    struct Date birthdate; // Nested structure
};


int main() {
    // Declare a variable of the outer structure type
    struct Student person1;

    // Assign values to the members of the outer structure
    strcpy(person1.name, "developer Indian");
    person1.age = 25;

    // Assign values to the members of the nested structure
    person1.birthdate.day = 15;
    person1.birthdate.month = 7;
    person1.birthdate.year = 1998;

    // Access and print the values
    printf("Name of student: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    printf("Birthdate: %d/%d/%d\n", person1.birthdate.day, person1.birthdate.month, person1.birthdate.year);

    return 0;
}


Conclusion

In this example, We learn nested struct with the Student structure represents a model in name , age , date of birth.
In the main function, we declare and initialize a student person  and name , class ,birth date . We then access and print the values of the nested structures.

Article