Chapter 6: Structures

page 127

There's one other piece of motivation behind structures that it's useful to discuss. Suppose we didn't have structures (or didn't know what they were or how to use them). Suppose we wanted to implement payroll records. We might set up a bunch of parallel arrays, holding the names, mailing addresses, social security numbers, and salaries of all of our employees:

	char *name[100];
	char *address[100];
	long ssn[100];
	float salary[100];
The idea here is that name[0], address[0], ssn[0], and salary[0] would describe one employee, array slots with subscript [1] would describe the second employee, etc. There are at least two problems with this scheme: first, if we someday want to handle more than 100 employees, we have to remember to change the size of several arrays. (Using a symbolic constant like
	#define MAXEMPLOYEES 100
would certainly help.)

More importantly, there would be no easy way to pass around all the information associated with a single employee. Suppose we wanted to write the function print_employee, which will print all the information associated with a particular employee. What arguments would this function take? We could pass it the index to use to retrieve the information from the arrays, but that would mean that all of the arrays would have to be global. We could pass the function an individual name, address, SSN, and salary, but that would mean that whenever we added a new piece of information to the database (perhaps next week we'll want to keep track of employee's shoe sizes), we would have to add another argument to the print_employee function, and change all of the calls. (Pretty soon, the number of arguments to the print_employee function would become unwieldy.) What we'd really like is a way to encapsulate all of the data about a single employee into a single data structure, so we could just pass that data structure around.

The right solution to this problem, in languages such as C which support the idea, is to define a structure describing an employee. We can make one array of these structures to describe all the employees, and we can pass around single instances of the structure where they're needed.

section 6.1: Basics of Structures

section 6.2: Structures and Functions

section 6.3: Arrays of Structures

The sizeof operator

section 6.4: Pointers to Structures

section 6.5: Self-referential Structures

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback