A structure is a composite data type in C programming that enables combining several data types under one name. A structure inside a structure is also called a nested structure. In this article, we will learn how to declare a structure inside a structure in C++.
Declare a Struct Inside a Struct in C
To declare a structure inside a structure, we need to first define the inner structure(the structure that we want to nest inside another structure) and then define the outer struct and include the inner struct as a member using the below syntax:
Syntax to Declare Nested Structure
struct innerStructName { //define inner structure }; struct outerStructName { struct innerStructName st; // inner struct as Direct member };
We can also declare it directly inside the parent structure:
struct outerStructName { struct innerStructName { //define inner structure }; };
C Program to Declare Struct Inside a Struct
The below program demonstrates how we can declare a nested structure and use it in C.
// C program to declare a structure inside a structure #include <stdio.h> // Declaring the inner struct struct InnerStruct {
char innerChar;
float innerFloat;
}; // Declaring the outer struct struct OuterStruct {
int outerData;
struct InnerStruct inner;
}; int main()
{ // Creating an instance of the outer struct
struct OuterStruct myStruct;
// Accessing and modifying the members of the inner
// struct
myStruct.inner.innerChar = 'X' ;
myStruct.inner.innerFloat = 5.14;
// Accessing the members of both the outer and
// inner structs
printf ( "Outer Data: %d\n" , myStruct.outerData);
printf ( "Inner Char: %c\n" , myStruct.inner.innerChar);
printf ( "Inner Float: %.2f\n" ,
myStruct.inner.innerFloat);
return 0;
} |
Outer Data: 0 Inner Char: X Inner Float: 5.14