Section 25.1 Intro to Structures
Up to this point we have been using the standard data types provided by C:
int, float, double, char, void
C also provides the capability to define your own data types. In particular, we’ll be learning about “structures”.
A structure is simply a collection of items of various data types into one single object.
Note that arrays on the other hand have to stick to one data type. Suppose we wanted to store some student data, for example, for each student:
char firstName[50];
char lastName[50];
int birthYear;
double aveGrade;
We could simply create four separate arrays: one that holds the first names, one for last names, etc. Structures make this much easier, however. We can store, in one variable, all of the data for one specific student. We can then simply create one array of students to hold all of the data we are interested in.
In the code window below you can see how to define such a
struct student
data type and how to subsequently use it in your code to declare variables me
and you
of this data type. You can also see how to initialize such a structure at declaration time and how to access the so-called members of the structure (so firstName
, lastName
, birthYear
, aveGrade
) in your code.