1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>15.4: Pointers to Structures
</title>
10 <link href=
"sx1c.html" rev=precedes
>
11 <link href=
"sx1e.html" rel=precedes
>
12 <link href=
"sx1.html" rev=subdocument
>
15 <H2>15.4: Pointers to Structures
</H2>
17 <p>[This section corresponds to K
&R Sec.
6.4]
18 </p><p>Pointers in C are general; we can have pointers to any type.
19 It turns out that pointers to structures are particularly useful.
20 </p><p>We declare pointers to structures
21 the same way we declare any other pointers:
22 by preceding the variable name with an asterisk in the declaration.
23 We could declare two pointers to
<TT>struct complex
</TT>
26 struct complex *p1, *p2;
29 we could set these pointers to point to actual variables of type complex:
38 would copy the structure pointed to by
<TT>p2
</TT>
39 to the structure pointed to by
<TT>p1
</TT>
40 (i.e.
<TT>c3
</TT> to
<TT>c2
</TT>),
45 would set
<TT>p1
</TT> to point wherever
<TT>p2
</TT> points.
47 these are the obvious analogs of how all
49 pointer assignments work.)
50 If we wanted to access the member of a pointed-to structure,
51 it would be a tiny bit messy--first
52 we'd have to use
<TT>*
</TT> to get the structure pointed to,
53 then
<TT>.
</TT> to access the desired member.
55 since
<TT>.
</TT> has higher precedence than
<TT>*
</TT>,
56 we'd have to use parentheses:
60 (Without the parentheses,
61 i.e. if we wrote simply
<TT>*p1.real
</TT>,
62 we'd be taking the structure
<TT>p1
</TT>,
63 selecting its member named
<TT>real
</TT>,
64 and accessing the value that
<TT>p1.real
</TT> points to,
65 which would be doubly nonfunctional,
66 since the
<TT>real
</TT> member is in our ongoing example not a pointer,
67 and
<TT>p1
</TT> is not a structure
68 but rather a pointer to a structure,
69 so the
<TT>.
</TT> operator won't work on it.)
70 </p><p>Since pointers to structures are common,
71 and the parentheses in the example above are a nuisance,
72 there's another structure selection operator
73 which works on pointers to structures.
74 If
<TT>p
</TT> is a pointer to a structure
75 and
<TT>m
</TT> is a member of that structure,
80 selects that member of the pointed-to structure.
81 The expression
<TT>p-
>m
</TT> is therefore exactly equivalent to
88 <a href=
"sx1c.html" rev=precedes
>prev
</a>
89 <a href=
"sx1e.html" rel=precedes
>next
</a>
90 <a href=
"sx1.html" rev=subdocument
>up
</a>
91 <a href=
"top.html">top
</a>
94 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
95 //
<a href=
"copyright.html">Copyright
</a> 1996-
1999
96 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>