A record is a package of variables, possibly of different types. Each variable is a field of the record. In C language, records are called structs, a shorthand for structure.
Table of contents:
The following example declares (that is, creates) a record x with three fields that can be used to store calendar dates:
struct { int day; int month; int year; } x;
It is a good ideia to give a name to the class of all records of a given kind. In our example, the name dmy seems appropriate:
struct dmy { int day; int month; int year; }; struct dmy x; // a record x of the dmy kind struct dmy y; // a record y of the dmy kind
To refer to a field of a record, just write the name of the record and the name of the field separated by a period:
x.day = 31; x.month = 12; x.year = 2020;
Records can be treated as
a new data type.
After the following definition, for example,
we can begin saying date
in place of struct dmy
:
typedef struct dmy date; date x, y;
Example. The following function computes the end date of an event upon receiving the beginning date of the event and its duration in days.
date eventend (date beginnig, int duration) { date end; . . . . . . end.day = ... end.month = ... end.year = ... return end; }
The code was omited because it is rather tedious, since it has to account for the number of days in different months and take into account the leap years. Here is how the function eventend could be used:
int main (void) {
date a, b;
scanf ("%d %d %d", &a.day, &a.month, &a.year);
// &a.day means &(a.day)
int duration;
scanf ("%d", &duration);
b = eventend (a, duration);
printf ("%d %d %d\n", b.day, b.month, b.year);
return EXIT_SUCCESS;
}
struct hm { int hours, minutes; };
Every record has an address in computer memory. (You may assume that the address of a record is the address of its first field.) The address of a record can be stored in a pointer. We say that such a pointer points to the record. For example,
date *p; // p is a pointer to dmy records date x; p = &x; // now p points to x (*p).day = 31; // same effect as x.day = 31
The expression p->day is a very useful shorthand for (*p).day . Hence, the last line of the code above could be written as
p->day = 31;
By the way, the meaning of (*p).day is very different from that of *(p.day) , which is equivalent to *p.day due to the precedence rules.
typedef struct { int p, q; } rational;
By convention, the q field of every rational is strictly positive and the greatest common divisor of the fields p and q is 1. Write functions
Answer: Yes. You can write
typedef struct dmy dmy; dmy x, y;