C - Putting structures within structures

Introduction

A structure can hold another structure as a member.

Demo

#include <stdio.h> 
#include <string.h> 

int main() /*from ww w.  j a  v a2s.c o  m*/
{ 
     struct date 
     { 
         int month; 
         int day; 
         int year; 
     }; 
     struct human 
     { 
         char name[45]; 
         struct date birthday; 
     }; 
     struct human president; 

     strcpy(president.name,"George Washington"); 
     president.birthday.month = 2; 
     president.birthday.day = 22; 
     president.birthday.year = 1732; 

     printf("%s was born on %d/%d/%d\n", 
             president.name, 
             president.birthday.month, 
             president.birthday.day, 
             president.birthday.year); 

     return(0); 
}

Result

The code above declares two structure types: date and human.

Within the human structure's declaration, you see the date structure variable birthday declared.

Then it creates a human structure variable, president.

The rest of the code fills that structure's members with data.

The structure's variable names are used; not the name that's used to declare the structure.

Related Topic