Tom Kelliher, CS18
Mar. 4, 1996
Compound?
What's another compound type?
Recall the Popcorn Co-Op
Suppose we had wanted to sort the data on the farm name after reading it in?
What would we use to store the records?
const int MAX_FARMS = 100; const int NAME_LEN = 30; char names[MAX_FARMS][NAME_LEN]; double acres[MAX_FARMS]; int pints[MAX_FARMS]; // Unix implementation assumed
What is the stronger relationship?
The problem? Consider:
swap(names[i], acres[i], pints[i], names[j], acres[j], pints[j]);
The Solution?
Allow association of variables of different types
Syntax of a structure declaration:
struct [structure tag]
{
member declaration;
...
} [structure variable definitions];
Examples:
struct rational // "struct rational" is a new type
{
int num; // "members" of the structure
int den;
};
struct rational a, b;
struct record // single record for popcorn Co-Op
{
char name[NAME_LEN];
double acres;
int pints;
};
struct record farms[MAX_FARMS]; // array of structures
swap(farms[i], farms[j]); // compare to previous swap
// structures passed
Important note: A structure is a type, not a variable
Key: . --- member operator
Similar to [] for arrays
Consider:
struct rational a,b;
struct record farms[MAX_FARMS];
a.num = 1;
a.den = 3;
a = b; // not implemented by a few compilers
i = 0;
while (!ifile.eof()) // ifile is associated with disk data file
{
ifile.getline(farms[i].name, NAME_LEN, ',');
ifile >> farms[i].acres;
ifile >> farms[i++].pints;
ifile.ignore;
}
struct rational a = { 1, 3 };
struct record farm = { "Orville's Acres", 114.8, 438010 };
struct record farms[2] = { { "Orville's Acres", 114.8, 438010 },
{ "Hoffman's Hills", 77.2, 36229 },
};
Valid operations:
Consider:
struct point // a 2-D point in the Cartesian plane
{
int x;
int y;
};
struct rectangle
{
struct point ll; // lower left point
struct point ur; // upper right point
{;