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; char *address; long ssn; float salary;The idea here is that name, address, ssn, and salary would describe one employee, array slots with subscript  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 100would 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