Nested Structure In C
In C, nested structures allow you to define one structure inside another. This helps organize related data logically, especially when a structure logically “belongs” to another structure.
Defining Nested Structures
There are two main methods used to define a structure in C programming
Method 01: Defining a structure directly within another structure.
Method 02: A structure can be defined separately and used as a member within another structure.
Method 01 Example: Defining Inside Another Structure
#include <stdio.h> struct Outer { int outerValue; struct Inner { int innerValue1; int innerValue2; } inner; }; int main() { struct Outer obj; obj.outerValue = 10; obj.inner.innerValue1 = 20; obj.inner.innerValue2 = 30; printf("Outer Value: %d\n", obj.outerValue); printf("Inner Values: %d, %d\n", obj.inner.innerValue1, obj.inner.innerValue2); return 0; }
Explanation:
Inner
is defined insideOuter
.- To access members of the inner structure, use
outer.inner.member
.
Output:
Outer Value: 10 Inner Values: 20, 30
Method 02 Example: Using an External Structure
#include <stdio.h> struct Inner { int innerValue1; int innerValue2; }; struct Outer { int outerValue; struct Inner inner; }; int main() { struct Outer obj; obj.outerValue = 50; obj.inner.innerValue1 = 60; obj.inner.innerValue2 = 70; printf("Outer Value: %d\n", obj.outerValue); printf("Inner Values: %d, %d\n", obj.inner.innerValue1, obj.inner.innerValue2); return 0; }
Explanation:
Inner
is defined as an independent structure.Outer
includesInner
as a member.- This approach allows
Inner
to be reused in other structures.
Output
Outer Value: 10 Inner Values: 20, 30
Nested Structure Key Points
- Accessing Members: Use the
.
operator for direct access, and->
if using pointers. - Scope: Structures defined inside another are limited to the containing structure’s scope.
- Reusability: Defining structures externally allows reuse in other structures.
This flexibility makes nested structures a powerful feature in C programming!