 |
Selection (structure-access) operators ('.' and '->') |
The C language supports two selection operators:
. (direct member selector)
-> (indirect, or pointer, member selector)
You use the selection operators '.'
and '->'
to access structure and union
members. Suppose that the object s is of struct type S and sptr is a pointer to
s. Then, if m is a member identifier of type M declared in S, these
expressions:
s.m
sptr->m
are of type M, and both represent the member object m in s.
The expression
sptr->m
is a convenient synonym for (*sptr).m
.
The direct member selector ('.'
) uses the following syntax:
expresssion . identifier
The expr must be of type union or structure.
The identifier must be the name of a member of that structure or union type.
The indirect member operator ('->'
) uses the following syntax:
expr -> identifier
The expr must be of type pointer to structure or pointer to union.
The identifier must be the name of a member of that structure or union type.
The expression with selection operators designates a member of a structure or union object. The
value of the selection expression is the value of the selected member; it will be an
lvalue if and only if the expr is an lvalue. For example,
struct mystruct
{
int i;
char str[21];
long d;
} s, *sptr=&s;
...
s.i = 3; // assign to the 'i' member of mystruct 's'
sptr->d = 12345678; // assign to the 'd' member of mystruct 's'
The expression 's.m'
is an lvalue, provided that 's'
is an lvalue and
'm'
is not an array type.
The expression 'sptr->m'
is an lvalue unless 'm'
is an array type.
If structure B contains a field whose type is structure A, the members of
A can be accessed by two applications of the member selectors.