20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Work<strong>in</strong>g with Po<strong>in</strong>ters and Structures<br />

243<br />

Once aga<strong>in</strong>, it should be po<strong>in</strong>ted out that there is no real motivation shown here as to<br />

why you should even bother us<strong>in</strong>g a structure po<strong>in</strong>ter when it seems as though you can<br />

get along just f<strong>in</strong>e without it (as you did <strong>in</strong> Program 9.1).You will discover the motivation<br />

shortly.<br />

Structures Conta<strong>in</strong><strong>in</strong>g Po<strong>in</strong>ters<br />

Naturally, a po<strong>in</strong>ter also can be a member of a structure. In the structure def<strong>in</strong>ition<br />

struct <strong>in</strong>tPtrs<br />

{<br />

<strong>in</strong>t *p1;<br />

<strong>in</strong>t *p2;<br />

};<br />

a structure called <strong>in</strong>tPtrs is def<strong>in</strong>ed to conta<strong>in</strong> two <strong>in</strong>teger po<strong>in</strong>ters, the first one called<br />

p1 and the second one p2.You can def<strong>in</strong>e a variable of type struct <strong>in</strong>tPtrs <strong>in</strong> the<br />

usual way:<br />

struct <strong>in</strong>tPtrs po<strong>in</strong>ters;<br />

The variable po<strong>in</strong>ters can now be used <strong>in</strong> the normal fashion, remember<strong>in</strong>g that<br />

po<strong>in</strong>ters itself is not a po<strong>in</strong>ter, but a structure variable that has two po<strong>in</strong>ters as its members.<br />

Program 11.5 shows how the <strong>in</strong>tPtrs structure can be handled <strong>in</strong> a C program.<br />

Program 11.5 Us<strong>in</strong>g Structures Conta<strong>in</strong><strong>in</strong>g Po<strong>in</strong>ters<br />

// Function to use structures conta<strong>in</strong><strong>in</strong>g po<strong>in</strong>ters<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

struct <strong>in</strong>tPtrs<br />

{<br />

<strong>in</strong>t *p1;<br />

<strong>in</strong>t *p2;<br />

};<br />

struct <strong>in</strong>tPtrs po<strong>in</strong>ters;<br />

<strong>in</strong>t i1 = 100, i2;<br />

po<strong>in</strong>ters.p1 = &i1;<br />

po<strong>in</strong>ters.p2 = &i2;<br />

*po<strong>in</strong>ters.p2 = -97;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!