Structure Member Access

Structure and union members are accessed using the following two selection operators:

The operator . is called the direct member selector and it is used to directly access one of the structure’s members. Suppose that the object s is of the struct type S and m is a member identifier of the type M declared in s, then the expression

s.m   // direct access to member m

is of the type M, and represents the member object m in S.

The operator -> is called the indirect (or pointer) member selector. Suppose that the object s is of the struct type S and ps is a pointer to s. Then if m is a member identifier of the type M declared in s, the expression

ps->m   // indirect access to member m;
        // identical to (*ps).m

is of the type M, and represents the member object m in s. The expression ps->m is a convenient shorthand for (*ps).m.

For example:

struct mystruct {
  int i;
  char str[21];
  double d;
} s, *sptr = &s;

...

s.i = 3;            // assign to the i member of mystruct s
sptr -> d = 1.23;   // assign to the d member of mystruct s

The expression s.m is lvalue, providing that s is lvalue and m is not an array type. The expression sptr->m is an lvalue unless m is an array type.

Accessing Nested Structures

If the structure B contains a field whose type is the structure A, the members of A can be accessed by two applications of the member selectors:

struct A {
  int j; double x;
};
struct B {
  int i; struct A aa; double d;
} s, *sptr;

...

s.i = 3;            // assign 3 to the i member of B
s.aa.j = 2;         // assign 2 to the j member of A
sptr->d = 1.23;     // assign 1.23 to the d member of B
sptr->aa.x = 3.14;  // assign 3.14 to x member of A

Structure Uniqueness

Each structure declaration introduces a unique structure type, so that in

struct A {
  int i,j; double d;
} aa, aaa;

struct B {
  int i,j; double d;
} bb;

the objects aa and aaa are both of the type struct A, but the objects aa and bb are of different structure types. Structures can be assigned only if the source and destination have the same type:

aa = aaa;    /* OK: same type, member by member assignment */
aa = bb;     /* ILLEGAL: different types */

/* but you can assign member by member: */
aa.i = bb.i;
aa.j = bb.j;
aa.d = bb.d;
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code