5.13.2. Using Structures

Use the following notation to work with structures and pointers to structures.

s . f

If s is a structure then s.f is the field called f in s. For example,
  Cell c;
  c.item = 20;
  c.name = "a cell";
creates structure c of type Cell (defined on the previous page) and stores 20 in its item field and string "a cell" in its name field.

Pointers to structure

There is a general rule in C++ that if p is a pointer of type T*, for some type T, then expression *p has type T. That rule applies to all types T, including structure types. For example, if p is created by
  PairOfInts x;
  PairOfInts* p = &x;
then p has type PairOfInts* and *p has type PairOfInts. So you can see that a pointer to a structure points to the entire structure. Structures are treated differently from arrays, where a pointer to an array is treated as a pointer to the first item in the array.

p->f

If p is a pointer to a structure then p->f abbreviates (*p).f. For example,
  Cell* p = new Cell;
  p->item = 20;
  p->name = "a cell";
creates a new Cell in the heap and initializes it.


Exercises

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

  2. Using the type Employee from exercise structure-1, 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

  3. What does p->size abbreviate? Answer