Sections 0101, 0102, 0103 and Honors, Fall 1995
Thursday December 7, 1995
Assigned Reading: 17.1
Handouts (available on-line): Quiz 3
Topics Covered:
- Structures (also called records) allow us to combine several
pieces of data with differing types under one variable name. In
our first example, we declare a new
type called student_record using the typedef
facility. Variables of the type student_record can hold
two strings and a double in the fields called name,
major and gpa. Sample run. If the variable
rec is of type student record, then the fields accessed
using rec.name, rec.major and
rec.gpa. These fields can then be used just like any
other string or double variable. ANSI C also allows us to pass
structures as parameters, use structures as return values from
functions, and assign one structure to another (older versions of
C do not).
- Our second example uses an
array of structures to hold information about a series of students.
Sample run.
- Our third example sorts
the array of structures according to the gpa field. Sample run. To do this, we modified
the sample run.) We did not need
to change this procedure very much. We just changed the type of
the array A and the type of the variable temp.
Also, in the FindSmallest function we compare
smallest_value against A[i]->gpa instead of
A[i]. Otherwise the new SelectionSort function is
identical to the old one.
- Finally, in our fourth example
we noted that our previous example did a lot of copying to
sort the array. For large records, this is very inefficient.
It would be much faster to sort an array of pointers to records
than an array of records, because when we swap two entries, we
just exchange the pointers instead of the entire record.
(See sample run.)
Here, it is convenient to define a new type of pointers called
rec_ptr which can point to a student_record.
Note that in this version, the function read_record
returns a pointer to student_record and not a student_record.
This makes sense because students is an array of pointers,
not an array of student_records. Thus, read_record
must call malloc to allocate a block of memory to store
the record it just read.
-
Quiz 3
Last Modified:
Thu Dec 7 16:39:09 EST 1995
Richard Chang, chang@gl.umbc.edu