Programming in C

(Barry) #1
Structures Containing Arrays 187

Naturally, it is possible to set up an array of dateAndTimestructures, as is done with the
following declaration:


struct dateAndTime events[100];


The array eventsis declared to contain 100 elements of type struct dateAndTime.The
fourth dateAndTimecontained within the array is referenced in the usual way as
events[3],and the ith date in the array can be sent to your dateUpdatefunction as fol-
lows:


events[i].sdate = dateUpdate (events[i].sdate);


To set the first time in the array to noon, the series of statements


events[0].stime.hour = 12;
events[0].stime.minutes = 0;
events[0].stime.seconds = 0;


can be used.


Structures Containing Arrays


As the heading of this section implies, it is possible to define structures that contain
arrays as members. One of the most common applications of this type is setting up an
array of characters inside a structure. For example, suppose you want to define a struc-
ture called monththat contains as its members the number of days in the month as well
as a three-character abbreviation for the month name.The following definition does
the job:


struct month
{
int numberOfDays;
char name[3];
};


This sets up a monthstructure that contains an integer member called numberOfDaysand
a character member called name.The member nameis actually an array of three charac-
ters.You can now define a variable to be of type struct monthin the normal fashion:


struct month aMonth;


You can set the proper fields inside aMonthfor January with the following sequence of
statements:


aMonth.numberOfDays = 31;
aMonth.name[0] = 'J';
aMonth.name[1] = 'a';
aMonth.name[2] = 'n';

Free download pdf