Next: , Up: Structures   [Contents][Index]

15.1 Referencing Structure Fields

To make a structure useful, there has to be a way to examine and store its fields. The ‘.’ (period) operator does that; its use looks like object.field.

Given this structure and variable,

struct intlistlink
    int datum;
    struct intlistlink *next;

struct intlistlink foo;

you can write foo.datum and to refer to the two fields in the value of foo. These fields are lvalues, so you can store values into them, and read the values out again.

Most often, structures are dynamically allocated (see the next section), and we refer to the objects via pointers. (*p).field is somewhat cumbersome, so there is an abbreviation: p->field. For instance, assume the program contains this declaration:

struct intlistlink *ptr;

You can write ptr->datum and ptr->next to refer to the two fields in the object that ptr points to.

If a unary operator precedes an expression using ‘->’, the ‘->’ nests inside:

  -ptr->datum   is equivalent to   -(ptr->datum)

You can intermix ‘->’ and ‘.’ without parentheses, as shown here:

struct { double d; struct intlistlink l; } foo;>next->datum