Just like all other data types (other than arrays, which are always passed by
reference), when structs are used as arguments they are passed by value.
This has the usual implication. Any changes made to an argument struct in a
function will not be visible at the point of call. Recall that this is
because, under call-by-value, a copy of each argument is made and passed along
to the called function.
We previously introduced call-by-reference as a technique to use when you want
changes made to a parameter to be reflected at the point of call. But with the
introduction of structs, there is another reason to use call-by-reference.
Copying an int, float, char, or pointer is not a big deal, since each is
relatively small (only a few bytes each). But copying an entire struct,
especially a big one, is a reasonably expensive proposition. How much memory
do you suppose that a struct ``person_info'' (from the examples in the
last lesson) takes up?
Click here for the answer
The solution is to pass a pointer to the struct, instead of the struct
itself. Because the pointer takes up only four bytes or so, that's a
big savings in copying. The called function can then access the
struct indirectly through the pointer. This is a useful thing to do
even if you aren't intending to modify the struct. For an example,
take a look at ``struct4.c'' in your ``examples'' directory (or
view it directly). How does it differ from
``struct3.c'' from the last lesson?
Click here for the answer
This is all fairly straightforward, assuming that you already understand
pointers. Take a look at the ``printf'' that makes up the body of
``writePerson''. Where we used to write, for example, ``p.first'', we now
write ``(*p).first''. Why?
Click here for the answer
Try two experiments. First change ``(*p).first'' to ``p.first.'' You should
receive an error message as explained in the last paragraph. Next try
changing it to ``*p.first'' (i.e., leave out the parentheses). Why do
you still get the error message?
Click here for the answer
Hamlet Project
hamlet@cs.utah.edu