Gaining Access to Structure Members

I l @ ve RuBoard

Gaining Access to Structure Members

A structure is like a "superarray," in which one element can be char , the next element float , and the next an int array. You can access the individual elements of an array by using a subscript. How do you access individual members of a structure? Use a dot ( . ), the structure member operator. For example, libry.value is the value portion of libry . You can use libry.value exactly as you would use any other float variable. Similarly, you can use libry.title exactly as you would use a char array. Therefore, the program uses expressions like

 gets(libry.title); 

and

 scanf("%f", &libry.value); 

In essence, .title , .author , and .value play the role of subscripts for a book structure.

Note that although libry is a structure, libry.value is a float type and is used like any other float type. For example, scanf("%f",...) requires the address of a float location, and that is what &libry.float is. The dot has higher precedence than the & here, so the expression is the same as &(libry.float) .

If you had a second structure variable of the same type, you would use the same method:

 struct book bill, newt; gets(bill.title); gets(newt.title); 

The .title refers to the first member of the book structure. Notice how in the initial program we printed the contents of the structure libry in two different formats. This illustrates the freedom you have in using the members of a structure. Now that you have these basics in hand, you're ready to expand your horizons and look at several ramifications of structures. You'll see arrays of structures, structures of structures, pointers to structures, and functions that process structures.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net