Sams Teach Yourself C in 21 Days

(singke) #1
Implementing Structures, Unions, and TypeDefs 275

11


This is repeated in the header for the function in line 34. When calling the function, you
only have to pass the structure instance name—in this case,rec(line 30). That’s all there
is to it. Passing a structure to a function isn’t very different from passing a simple vari-
able.
You can also pass a structure to a function by passing the structure’s address (that is, a
pointer to the structure). In fact, in older versions of C, this was the only way to pass a
structure as an argument. It’s not necessary now, but you might see older programs that
still use this method. If you pass a pointer to a structure as an argument, remember that
you must use the indirect membership operator (->) to access structure members in the
function.

DOtake advantage of declaring a
pointer to a structure—especially when
using arrays of structures.
DOuse the indirect membership opera-
tor (->) when working with a pointer to
a structure.

DON’Tconfuse arrays with structures.
DON’Tforget that when you increment a
pointer, it moves a distance equivalent to
the size of the data to which it points. In
the case of a pointer to a structure, this
is the size of the structure.

DO DON’T


Understanding Unions ........................................................................................


Unionsare similar to structures. A union is declared and used in the same ways that a
structure is. A union differs from a structure in that only one of its members can be used
at a time. The reason for this is simple. All the members of a union occupy the same area
of memory—they are laid on top of one another.

Defining, Declaring, and Initializing Unions ................................................

Unions are defined and declared in the same fashion as structures. The only difference in
the declarations is that the keyword unionis used instead of struct. To define a simple
union of a charvariable and an integer variable, you would write the following:
union shared
{
char c;
int i;
};
This union,shared, can be used to create instances of a union that can hold either a char-
acter value cor an integer value i. This is an ORcondition. Unlike a structure that would

18 448201x-CH11 8/13/02 11:17 AM Page 275

Free download pdf