Nested Structures

I l @ ve RuBoard

Nested Structures

Sometimes it is convenient for one structure to contain, or nest, another. For example, Shalala Pirosky is building a structure of information about her friends . One member of the structure, naturally enough, is the friend's name. The name, however, can be represented by a structure itself, with separate entries for first and last name members . Listing 14.3 is a condensed example of Shalala's work.

Listing 14.3 The friend.c program.
 /* friend.c -- example of a nested structure */ #include <stdio.h> #define LEN 20 const char * msgs[5] = {     "    Thank you for the wonderful evening, ",     "You certainly prove that a ",     "is a special kind of guy. We must get together",     "over a delicious ",     " and have a few laughs" }; struct names {                     /* first template        */     char first[LEN];     char last[LEN]; }; struct guy {                       /* second template       */     struct names handle;           /* nested structure      */     char favfood[LEN];     char job[LEN];     float income; }; int main(void) {     struct guy fellow = {   /* initialize a variable */         { "Chip", "Vejer" },         "nachos plate",         "memory broker",          36827.00     };     printf("Dear %s, \n\n", fellow.handle.first);     printf("%s%s.\n", msgs[0], fellow.handle.first);     printf("%s%s\n", msgs[1], fellow.job);     printf("%s\n", msgs[2]);     printf("%s%s%s", msgs[3], fellow.favfood, msgs[4]);     if (fellow.income > 150000.0)         puts("!!");     else if (fellow.income > 75000.0)         puts("!");     else         puts(".");     printf("\n%40s%s\n", " ", "See you soon,");     printf("%40s%s\n", " ", "Shalala");     return 0; } 

Here is the output:

 Dear Chip,     Thank you for the wonderful evening, Chip. You certainly prove that a memory broker is a special kind of guy. We must get together over a delicious nachos plate and have a few laughs.                                         See you soon,                                         Shalala 

First, note how the nested structure is set up in the template. It is simply declared, just as an int variable would be:

 struct names handle; 

This declaration says that handle is a variable of the struct names type. Of course, the file should also include the declaration for the names structure.

Second, note how you gain access to a member of a nested structure; you merely use the dot operator twice:

 fellow.handle.first == "Chip" 

The construction is interpreted this way, going from left to right:

 (fellow.handle).first 

That is, find fellow , then find the handle member of fellow , and then find the first member of that.

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