Programming in C

(Barry) #1
Working with Pointers and Structures 243

Once again, it should be pointed out that there is no real motivation shown here as to
why you should even bother using a structure pointer when it seems as though you can
get along just fine without it (as you did in Program 9.1).You will discover the motiva-
tion shortly.


Structures Containing Pointers


Naturally, a pointer also can be a member of a structure. In the structure definition


struct intPtrs
{
int p1;
int
p2;
};


a structure called intPtrsis defined to contain two integer pointers, the first one called
p1and the second one p2.You can define a variable of type struct intPtrsin the
usual way:


struct intPtrs pointers;


The variable pointerscan now be used in the normal fashion, remembering that
pointersitself is nota pointer, but a structure variable that has two pointers as its mem-
bers.
Program 11.5 shows how the intPtrsstructure can be handled in a C program.


Program 11.5 Using Structures Containing Pointers


// Function to use structures containing pointers


#include <stdio.h>


int main (void)
{
struct intPtrs
{
int p1;
int
p2;
};


struct intPtrs pointers;
int i1 = 100, i2;

pointers.p1 = &i1;
pointers.p2 = &i2;
*pointers.p2 = -97;
Free download pdf