6.3 Accessing the members of Structures


Objectives:

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

Show and modify the structure members

The operator used to access structure members are dot operator and arrow operator.

Using dot (.) operator

To access structure members, the operator used is the dot operator denoted by (.). The dot operator for accessing structure members is used thusly:

Consider the example below:



6.3 Accessing the members of Structures


Once we have declared our three objects of a determined structure type (apple, banana and melon) we can operate directly with their members. To do that we use a dot (.) inserted between the object name and the member name. For example, we could operate with any of these elements as if they were standard variables of their respective types:


Each one of these has the data type corresponding to the member they refer to: apple.weight, banana.weight and melon.weight are of type int, while apple.price, banana.price and melon.price are of type float.

For example:

A programmer wants to assign 2000 for the structure member weight in the above example of structure Product with object name apple this is written as:


6.3 Accessing the members of Structures



Let's see a real example where you can see how a structure type can be used in the same way as fundamental types:


6.3 Accessing the members of Structures


Example 6.2 : Example about structure

                    continue next page..

6.3 Accessing the members of Structures



The example shows how we can use the members of an object as regular variables. For example, the member yours.year is a valid variable of type int, and mine.title is a valid variable of type string.

The objects mine and yours can also be treated as valid variables of type movies_t, for example we have passed them to the function printmovie as we would have done with regular variables. Therefore, one of the most important advantages of data structures is that we can either refer to their members individually or to the entire structure as a block with only one identifier.

6.3 Accessing the members of Structures


Using Arrow Operator

When using a pointer to a struct, the “->” (arrow) operator is typically used as a more readable way to both dereference the pointer and select a member.

Assume the following declaration



6.3 Accessing the members of Structures


The following are equivalent with above.