Structures: A Compound Data Type

Tom Kelliher, CS18

Mar. 4, 1996

Compound?

What's another compound type?

Data Structure Design

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?

Structures

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

Referencing Structure Members

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;
}

Initializing Structure Members

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 },
                         };

Operations on Structure Variables

Valid operations:

  1. Assigning the value of one structure variable to another of the same type (name equivalency)
  2. Passing structure variables, returning structure values
  3. Applying the member operator to a structure variable (valid operations on resulting l/rvalue?)
  4. Taking the address of a structure ( &)

Nested Structures

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
{;

Exercises

  1. For struct rational, write a function which takes two rational value parameters and computes and return their sum through a third rational reference parameter.
  2. For struct rectangle, write a function which returns the area of a rectangle passed by value. How general is your function? (It should work even if the two points are interchanged.)


Thomas P. Kelliher
Fri Mar 1 08:00:07 EST 1996
Tom Kelliher