27C. Referring to Fields of Structures


Variables of a structure type

Suppose that r has type PairOfInts. Then r.a and r.b refer to the a and b fields of r. For example,

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


Pointers to structures

Suppose that p is a pointer of type PairOfInts* that has been initialized to point to a structure as follows.

  PairOfInts* p = new PairOfInts;

Then *p is the structure that p points to, and (*p).a is the a field of *p, and

  (*p).a = 25;
stores 25 into the a field of *p.

Unfortunately, the dot operator has higher precedence than the unary * operator, which means that the parentheses are required in (*p).a; expression *p.a does not work. To avoid that cumbersome notation, C++ offers an abbreviation:

p->a abbreviates (*p).a

Statement

  p->a = 25;
has the exact same meaning as
  (*p).a = 25;
but it is easier to read (once you have become familiar with the notation).

Should I use dot or arrow?

If x has a structure type, such as PairOfInts or Cell, use a dot: x.field.

If the type of y a pointer to a structure, such as PairOfInts* or Cell*, use a arrow: y->field.


Exercises

  1. Using the type Employee from a 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

  2. Repeat the preceding exercise, but this time allocate the structure in the heap. Answer