DEV Community

mikkel250
mikkel250

Posted on

Nested structures in C

Nested structures

C also allows you to define a structure that itself contains other structures as one or more of its members. If the program you're working on required a timestamp, a convenient way to associate both together would be to define a new structure that contains both time and date as its member elements:

struct dateAndTime
{
  struct date sDate;
  struct time sTime;
};
Enter fullscreen mode Exit fullscreen mode

You could now create an instance of dateAndTime that contains both date and time structures:

struct dateAndTime timestamp;

// to access the members, dot notation is used as usual:
timestamp.sDate;

// to reference a particular member inside one of these structures, the same syntax is used:
timestamp.sDate.month = 10;

// increments the seconds inside the sTime member of dateAndTime
++timestamp.sTime.seconds;

// initialization of both date and time inside timestamp
// sets the date to February 1st, 2018 at 3:30:00
struct dateAndTime timestamp = { {2, 1, 2018}, {3, 30, 0} };

// just like other structures, the dot notation can be used to initialize specific member's variables
// and, though it is more typing, is more readable. It is order independent:
struct dateAndTime timestamp = {
  {.month = 2, .day = 1, .year = 2018},
  {.hour = 3, .minutes = 30, .seconds = 0}
};
Enter fullscreen mode Exit fullscreen mode

It is also possible to create an array of dateAndTime structures. The array index along with dot notation are used, in the same way as with a non-nested structure within the array:

struct dateAndTime timestamp[100];

timestamp[0].sTime.hour = 3;
timestamp[0].sTime.minutes = 30;
timestamp[0].sTime.seconds = 0;
Enter fullscreen mode Exit fullscreen mode

It is possible declare a structure within a structure within the actual definition, it follows the same syntax as declaring a structure variable during the definition, but IMO this is not as readable as the longer ways of declaring them, but as with most things, is a matter of personal preference:

struct time
{
  struct date
  {
    int day;
    int month;
    int year;
  } dateOfBirth;

  int hour;
  int minute;
  int seconds;
}
Enter fullscreen mode Exit fullscreen mode

The declaration above is enclosed inside the scope of the time structure definition, and does not exist outside of it. You would not be able to declare a date variable external to the time structure.

Top comments (0)