How to Declare a Struct Inside a Struct in C?
Last Updated :
13 Feb, 2024
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
#include <stdio.h>
struct InnerStruct {
char innerChar;
float innerFloat;
};
struct OuterStruct {
int outerData;
struct InnerStruct inner;
};
int main()
{
struct OuterStruct myStruct;
myStruct.inner.innerChar = 'X' ;
myStruct.inner.innerFloat = 5.14;
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;
}
|
Output
Outer Data: 0
Inner Char: X
Inner Float: 5.14
Share your thoughts in the comments
Please Login to comment...