6.6 Pointers to Structures


Objectives:

At the end of this lesson you will be able to:

Use pointers to structures

Like any other type, structures can be pointed by its own type of pointers:


Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects of structure type movies_t. So, the following code would also be valid:



6.6 Pointers to Structures


The value of the pointer pmovie would be assigned to a reference to the object amovie (its memory address).

We will now go with another example that includes pointers, which will serve to introduce a new operator: the arrow operator (->):

Example 6.4: Pointers to structures



6.6 Pointers to Structures



The previous code includes an important introduction: the arrow operator (->). This is a dereference operator that is used exclusively with pointers to objects with members. This operator serves to access a member of an object to which we have a reference. In the example we used:



6.6 Pointers to Structures


Which is for all purposes equivalent to:


Both expressions pmovie->title and (*pmovie).title are valid and both mean that we are evaluating the member title of the data structure pointed by a pointer called pmovie. It must be clearly differentiated from:


which is equivalent to:


And that would access the value pointed by a hypothetical pointer member called title of the structure object pmovie (which in this case would not be a pointer). The following panel summarizes possible combinations of pointers and structure members:


6.6 Pointers to Structures