| CSC 161 | Grinnell College | Spring, 2012 |
| Imperative Problem Solving and Data Structures | ||
The following commentary comes from Marge Coahran with minor editing.
A struct in C is the same as a record in many other (pre- object-oriented) programming languages. A struct is a collection of data. Functions that operate on a struct are not embedded within the struct; rather, we write such functions separately and pass structs to them as arguments.
For example, a program for keeping track of students might use the following collection of variables:
struct student {
int number;
double testGrades[2];
double grade;
};
The struct is named student while its members
are number, testGrades, and grade.
The name of a struct is also called a tag.
A later declaration of
struct student hannah;
will create a structure variable named hannah. The individual
member variables can be referred to using the syntax
variableName.memberName, as in the following example:
hannah.number = 991234567;
hannah.testGrades[0] = 10.;
hannah.testGrades[1] = 11.;
hannah.grade = (hannah.testGrades[0] / 15. + hannah.testGrades[1] / 12.) / 2.;
The declaration
struct student csc201[30];
might be used to create an array of student records.
Alternatively, we can define a new data type to describe our student information, using the instruction:
typedef struct {
int number;
double testGrades[2];
double grade;
} student_t;
and then declare our variables using this new type, with instructions like:
student_t hannah;
student_t csc201[300];
You might find it helpful to think of the typedef
instruction as giving a "blueprint" for the creation of a
student_t struct variable,
while the declarations cause the "construction" of variables having type
student_t by setting aside memory.
The following struct may be used to represent a time value in hours, minutes and seconds format (e.g., 12:34:56.123):
typedef struct {
int hours;
int mins;
double secs;
} timeinfo_t;
The timeinfo_t identifier
is the struct "tag". A new type called timeinfo_t is created.
We did not call it time, because there is already a C library
function called time.
Structure types may be used as return types or argument types in functions. A function that converts time values given in seconds (e.g., 12345.67) to time values given in hh:mm:ss.sss format might have the prototype:
timeinfo_t convertTime( double realTime )
and would look like:
timeinfo_t convertTime( double realTime )
{
timeinfo_t result;
.
.
.
return result;
}