
CMSC 216 Practice Exam #2 Fall 2010
1. [45 pts.] Consider the following structure type:
typedef struct {
char *name;
float shoe_size;
int *age;
} Student;
Write the two functions described below:
Student **read_students(void);
void destroy_students(Student **s);
•The function read students() should read data about students and return a pointer to a
dynamically–allocated array storing the data read:
–Your function should read until the end of the input is seen, where each input line contains
the data for one student, consisting of a name (a single word which will always be less than 21
characters), a shoe size (a float), and an age (an integer), each separated by a single space.
–Recall that the scanf() function will read a string using the %s format specifier, and scanf()
will return EOF if the end of the input is detected. Therefore a loop like the following will read
the input, assuming name,foot magnitude, and years old are declared appropriately.
while (scanf("%s %f %d", name, &foot_magnitude, &years_old) != EOF) {
/* process the line of input which was read */
}
–You may assume that the input will always be valid and of the form described, and when your
function is called there will be one or more lines of input to be read.
–Although you may assume there will be at least one line of input, other than that you have no
idea how many lines of input there will be– there could be any number (but you can assume
all the data will fit into memory).
–Your function must return a pointer to an array that has exactly one element more than the
number of lines in the input. Each element should be a pointer to a Student structure.
The last element of the array must contain NULL, so the caller can tell where the end of the data
is.
As it works, your function may create arrays of whatever size you want, but when it leaves,
it must return an array of exactly the size described, namely with one more element than the
number of lines in the input.
–Each student’s name must be stored in a dynamically–allocated array (that the name field in a
Student structure will point to) that is exactly the right size needed to store that name. The
student’s age will also be stored in a dynamically–allocated int, for no real good reason except
that we want it that way.
–To make things simpler you may assume that all memory allocations will always be successful.
–We don’t care how efficient (or inefficient) your function is.
–Note that the function has to deal with a gazillion pointers – it must create a dynamically–
allocated array of pointers, where each pointer in the array points to a dynamically–allocated
Student structure. Each Student structure contains two dynamically–allocated fields (a stu-
dent’s name and age).