c
  1. c-nested-structures

C Nested Structures

Syntax

The syntax for a nested structure in C is as follows:

struct outer {
    int a;
    struct inner {
        int b;
        int c;
    } s;
} t;

Example

#include <stdio.h>

int main() {
    struct outer {
        int a;
        struct inner {
            int b;
            int c;
        } s;
    } t;
    
    t.a = 10;
    t.s.b = 20;
    t.s.c = 30;
    
    printf("a = %d\n", t.a);
    printf("b = %d\n", t.s.b);
    printf("c = %d\n", t.s.c);
    
    return 0;
}

Output

The output of the above example will be:

a = 10
b = 20
c = 30

Explanation

A nested structure is a structure within another structure. In the above example, we have an outer structure that has a member variable a of type int and an inner structure s which has two member variables b and c of type int.

We created an object t of the outer structure and set the values of its member variables a, s.b, and s.c. We then printed the values of these variables using printf() statements.

Use

Nested structures can be used to group related data together in a structured way. They can help to organize code and make it more readable, especially when dealing with complex data structures.

Important Points

  • The members of a nested structure can be accessed using the dot (.) operator.
  • In a nested structure, the inner structure must be defined before it can be used in the outer structure.
  • A nested structure can also be defined outside of the outer structure, and can then be included in the outer structure as a member variable.

Summary

A nested structure is a structure that is defined within another structure. It can be used to group related data together and can help to organize code and make it more readable. The inner structure can be accessed using the dot (.) operator and must be defined before it can be used in the outer structure. By using nested structures, you can create complex data structures that are easy to use and maintain.

Published on: