CSC 161 Grinnell College Fall, 2011 Imperative Problem Solving and Data Structures

# Structures in C — structs

The following commentary comes from Marge Coahran with minor editing.

### Some Background

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, and 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;
};
```
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 John;
```
will create a structure variable named `John`. The individual member variables can be referred to using the syntax `variableName.memberName`, as in the following example:
```    John.number = 991234567;
John.grade  = (John.testGrades / 15. + John.testGrades / 12.) / 2.;

```

The declaration

```    struct student csc201;
```
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;
} student_t;

```
and then declare our variables using this new type, with instructions like:
```    student_t John;
student_t csc201;
```

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.

### Representing Time with a Struct

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. I didn't 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;
}
```