15.4: Pointers to Structures

[This section corresponds to K&R Sec. 6.4]

Pointers in C are general; we can have pointers to any type. It turns out that pointers to structures are particularly useful.

We declare pointers to structures the same way we declare any other pointers: by preceding the variable name with an asterisk in the declaration. We could declare two pointers to struct complex with

	struct complex *p1, *p2;
And, as before, we could set these pointers to point to actual variables of type complex:
	p1 = &c2;
	p2 = &c3;
Then,
	*p1 = *p2
would copy the structure pointed to by p2 to the structure pointed to by p1 (i.e. c3 to c2), and
	p1 = p2
would set p1 to point wherever p2 points. (None of this is new, these are the obvious analogs of how all pointer assignments work.) If we wanted to access the member of a pointed-to structure, it would be a tiny bit messy--first we'd have to use * to get the structure pointed to, then . to access the desired member. Furthermore, since . has higher precedence than *, we'd have to use parentheses:
	(*p1).real
(Without the parentheses, i.e. if we wrote simply *p1.real, we'd be taking the structure p1, selecting its member named real, and accessing the value that p1.real points to, which would be doubly nonfunctional, since the real member is in our ongoing example not a pointer, and p1 is not a structure but rather a pointer to a structure, so the . operator won't work on it.)

Since pointers to structures are common, and the parentheses in the example above are a nuisance, there's another structure selection operator which works on pointers to structures. If p is a pointer to a structure and m is a member of that structure, then

	p->m
selects that member of the pointed-to structure. The expression p->m is therefore exactly equivalent to
	(*p).m


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1996-1999 // mail feedback