Frequently, one needs a compound type where the different parts of the compound have different types. These different parts are called fields. This data object is called a structure, and is declared according to the following pattern:
struct tag { declaration list } variable_list;
where:
struct is the keyword for structures tag is an optional identifier which gives a unique tag name to this particular structure being declared declaration list is a list of declarations, i.e. types followed by field names (perhaps with a list separated by commas for the same type) and type-name_list pairs separated by a semicolon variable_list is an optional list of comma separated identifiers each of which will have type "struct" tag ending semicolon, ;, as with all declarations.>p>Let us give a concrete example illustrating all of the possible options.
struct student { char name[40]; int age, /* in months */ height; /* in centimeters */ float weight; /* in kg */ struct student *next; } assistant, class[12], *first;
which means: the structure with tag name student has 5 fields. They are (in words):
an array of 40 char called name a int called age, and one called height a float called weight a pointer to struct student called next
Lastly, three variables have been declared to be type struct student, one called assistant, and another called class which is actually an array of 12 structs with tag name'student, and first which is of type pointer to struct student. The last field, named next could be used to build a linked list of students starting with first.
The only operations allowed on whole structures is assignment, provided both the left side and right side are of the same structure type.
To refer to the fields of a structure, the field selection operator period, ., is used. Thus from the above example:
assistant.height
is of type "int" it is the height of the student assistant, while:
class[3].name
is of type pointer tochar (or: char *), and its value is the address of the array of characters which is the name of the fourth, i.e. index value 3, student in the array class.
If instead of an identifier whose type is struct we have a pointer to struct then, to select the height field, we can either write:
(*first).height
or use the abbreviation:
first->height
Although the abbreviation only saves one of four keystrokes, its main advantage visually is the operator is sequentially in one place and hence is clearer.