Sams Teach Yourself C in 21 Days

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

11


char *p_message;
p_message = “Teach Yourself C In 21 Days”;
You can do the same thing with pointers to type charthat are structure members:
struct msg {
char *p1;
char *p2;
} myptrs;
myptrs.p1 = “Teach Yourself C In 21 Days”;
myptrs.p2 = “By SAMS Publishing”;
Figure 11.4 illustrates the result of executing these statements. Each pointer member of
the structure points to the first byte of a string, stored elsewhere in memory. Contrast this
with Figure 11.3, which shows how data is stored in a structure that contains arrays of
typechar.

FIGURE11.4
A structure that con-
tains pointers to type
char.

1008
2252

myptrs
myptrs.p1
myptrs.p2

Teach Yourself C In 21 Days\0

By SAMS Publishing\0

1008 1009....

2252 2253....

You can use pointer structure members anywhere a pointer can be used. For example, to
print the pointed-to strings, you would write
printf(“%s %s”, myptrs.p1, myptrs.p2);
What’s the difference between using an array of type charas a structure member and
using a pointer to type char? These are both methods for “storing” a string in a structure,
as shown here in the structure msg, which uses both methods:
struct msg
{
char p1[30];
char *p2; /* caution: uninitialized */
} myptrs;
Recall that an array name without brackets is a pointer to the first array element.
Therefore, you can use these two structure members in similar fashion (note that p2
should be initialized before you copy a value to it):

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

Free download pdf