Sams Teach Yourself C in 21 Days

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

11


26: {
27: /* Initialize the pointer to the first array element. */
28:
29: p_part = data;
30:
31: /* Loop through the array, incrementing the pointer */
32: /* with each iteration. */
33:
34: for (count = 0; count < MAX; count++)
35: {
36: printf(“At address %d: %d %s\n”, p_part, p_part->number,
37: p_part->name);
38: p_part++;
39: }
40:
41: return 0;
42: }

At address 4202504: 1 Smith
At address 4202516: 2 Jones
At address 4202528: 3 Adams
At address 4202540: 4 Wilson
First, in lines 11 through 18, this program declares and initializes an array of part
structures called data. A pointer called p_partis then defined in line 22 to be
used to point to the datastructure. The main()function’s first task in line 29 is to set the
pointer,p_part, to point to the partstructure that was declared. All the elements are
then printed using a forloop in lines 34 through 39 that increments the pointer to the
array with each iteration. The program also displays the address of each element.
Look closely at the addresses displayed. The precise values might differ on your system,
but they are in equal-sized increments—just the size of the structure part. This clearly
illustrates that incrementing a pointer increases it by an amount equal to the size of the
data object it points to.

Passing Structures as Arguments to Functions ............................................

Like other data types, a structure can be passed as an argument to a function. Listing
11.6 shows how to do this. This program is a modification of the program shown in
Listing 11.3. It uses a function to display information on the screen from a structure that
is passed in, whereas Listing 11.3 uses statements that are part of main().

LISTING11.5 continued

OUTPUT

ANALYSIS

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

Free download pdf