22C. Pointers to Structures

We have seen that, if p has type T*, then *p has type T. That holds for every type T, including for structure types.

Suppose that you create variable p and make it point to a new Cell, as follows.

  Cell* p;
  p = new Cell;

Since p has type Cell*, expression *p has type Cell. Clearly, *p is the cell that p points to. To select the item field, use (*p).item. For example,

  (*p).item = 25;
stores 25 into the item field of the item pointed to by p.

The dot operator has higher precedence than the star operator, so the parentheses in (*p).item are required.

Expression (*p).item works, but it is cumbersome. C++ provides an alternative notation that most people prefer.

Expression p->item abbreviates (*p).item.

That is, the -> operator is a combination of a star and a dot. For example, statement

  p->item = 25;
means the same thing as
  (*p).item = 25;

Operator -> is done from left to right. That is, p->a->b means the same thing as (p->a)->b. We will take advantage of that when working with linked lists.


Exercises

  1. What does p->size abbreviate? Answer

  2. What is the difference between . and -> for structure? Answer

  3. When you create a variable of type Cell*, do you also need to say new Cell? Answer

  4. Using type Employee from a prior exercise, write statements that create a pointer to an Employee called Philp, makes Philp point to a newly allocated Employee in the heap, and then sets *Philp's name to "Phil", salary to 80,000 and office to "232D". Answer

  5. Add a constructor to type Employee that takes three parameters and stores them into the name, salary and office parts of the structure. Then write a statement creates an Employee as in the preceding exercise, but use the constructor. Answer