22A. Structures


Structured values

A structured value is a collection of variables, called fields, each with a name and a type. For example, a structured value might contain an integer called item and a const char* pointer called name, as shown in the following diagram.

Structured values (or simply structures) are useful because they allow you to group values and to treat the group as a single value.


Structure types

Each structured value has a type that must be defined within the program. Define a type of structures using struct. For example,

  struct PairOfInts
  {
    int a;
    int b;
  };
creates a new type PairOfInts, where a value of type PairOfInts has two fields, called a and b, each of type int. Type definition
  struct Cell
  {
    int         item;
    const char* name;
  };
defines type Cell with two fields, corresponding to the diagram above. (Remark: The const designator for field name indicates that the characters in array name cannot be changed. You are free to store a different pointer of type const char* into a structure of type Cell.)

Notice the semicolon at the end of a structure type definition. Be sure to include it.


Where to define structure types

If module A.cpp exports a structure type, put the type definition in A.h, and only in A.h. If A.cpp does not export the structure type, put the type definition near the beginning of A.cpp.


Creating structured values

Create a structured value the way you would create any variable. For example, statements

  PairOfInts p;
  Cell c;
create a variable p of type PairOfInts and a variable c of type Cell.


Referring to fields

Use p.a and p.b to refer to the a and b fields of structured value p. For example,

  PairOfInts p;
  p.a = 100;
  p.b = 200;
creates and initializes a structured value.


Allocating structures

A structure allocated using

  Cell c;
is stored in the frame of the current function, and is destroyed when the function returns. To allocate a structure that lives longer than the function that created it, use new. First, let's just create a pointer variable.
  Cell* p;
Notice that p is not yet initialized, and contains a junk address.

Now we initialize p to point to newly allocated memory.

  p = new Cell;


Exercises

  1. A string is an array of characters, so it has type char*.

    Write a definition of structure type Employee, where a value of type Employee has three fields: (1) a constant null-terminated string called name, (2) a value of type double called salary and (3) a constant null-terminated string called office.

    Answer

  2. Using the type Employee from the preceding exercise, write statements that create an Employee called Phil and that sets Phil's name to "Phil", salary to 80,000 and office to "232D". Answer