nested structures in c code example

Example 1: how to put a struct in another struct C

struct B {  // <-- declare before
  int number;
};
struct A {
 int data;
 B b; // <--- declare data member of `B`
 };

Example 2: structure within structure

#include <stdio.h>
#include <string.h>
 
struct student_college_detail
{
    int college_id;
    char college_name[50];
};
 
struct student_detail 
{
    int id;
    char name[20];
    float percentage;
    // structure within structure
    struct student_college_detail clg_data;
}stu_data;
 
int main() 
{
    struct student_detail stu_data = {1, "Raju", 90.5, 71145,
                                       "Anna University"};
    printf(" Id is: %d \n", stu_data.id);
    printf(" Name is: %s \n", stu_data.name);
    printf(" Percentage is: %f \n\n", stu_data.percentage);
 
    printf(" College Id is: %d \n", 
                    stu_data.clg_data.college_id);
    printf(" College Name is: %s \n", 
                    stu_data.clg_data.college_name);
    return 0;
}

Example 3: how we can strore a nested structure values in arrays

typedef struct {

    char ChannelNo[3];              //"P1"
    unsigned int ChannelPin;        //23
    char State;                     //'o'
}test;

typedef struct {

    test One[3];
    test two[3];
    test three[3];
    test four[3];
    test five;
    test six[3];

}matrix;

matrix x[] =
    {
    // [0]
        {
            .One = {
                     {.ChannelNo = "P4", .ChannelPin = 23, .State = 'o'},
                     {.ChannelNo = "P1", .ChannelPin = 98, .State = 'o'},
                     {.ChannelNo = "P0", .ChannelPin = 23, .State = 'o'},
            },
            .two = {
                    {.ChannelNo = "P5", .ChannelPin = 79, .State = 'd'},
                    {.ChannelNo = "P4", .ChannelPin = 79, .State = 'e'},
                    {.ChannelNo = "P5", .ChannelPin = 79, .State = 'r'},
            },
            // ......
            .five = {.ChannelNo = "P5", .ChannelPin = 79, .State = 'r'},
        },
    // [1]
        {
            .One = {
                     {.ChannelNo = "P4", .ChannelPin = 23, .State = 'o'},
                     {.ChannelNo = "P1", .ChannelPin = 98, .State = 'o'},
                     {.ChannelNo = "P0", .ChannelPin = 23, .State = 'o'},
            },
            .two = {
                    {.ChannelNo = "P5", .ChannelPin = 79, .State = 'd'},
                    {.ChannelNo = "P4", .ChannelPin = 79, .State = 'e'},
                    {.ChannelNo = "P5", .ChannelPin = 79, .State = 'r'},
            },
            // ......
            .five = {.ChannelNo = "P5", .ChannelPin = 79, .State = 'r'},
        },
    // ......
    };

Tags:

C Example