C - Structure Structure Nesting

Introduction

You can define a structure type designed to hold dates.

Then you can specify a suitable structure with the tag name Date with this statement:

struct Date
{
  int day;
  int month;
  int year;
};

You can include a typedef for Date as well as for Dog:

typedef struct Dog Dog;       // Define Dog as a type name
typedef struct Date Date;         // Define Date as a type name

Now you can define the Dog structure, including a date-of-birth variable, like this:

struct Dog
{
  Date dob;
  int height;
  char name[20];
  char father[20];
  char mother[20];
};

Next, you can define an instance of the Dog structure with the usual statement:

Dog d1;
d1.height = 14;

To set the date of birth in a series of assignment statements, you can use the logical extension of this notation:

d1.dob.day = 5;
d1.dob.month = 12;
d1.dob.year = 2010;

Related Topics

Exercise