当前位置:嗨网首页>书籍在线阅读

12-嵌套结构

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

14.5 嵌套结构

有时,在一个结构中包含另一个结构(即嵌套结构)很方便。例如,Shalala Pirosky创建了一个有关她朋友信息的结构。显然,结构中需要一个成员表示朋友的姓名。然而,名字可以用一个数组来表示,其中包含名和姓这两个成员。程序清单14.3是一个简单的示例。

程序清单14.3  friend.c 程序

// friend.c -- 嵌套结构示例
#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 {                   // 第1个结构
     char first[LEN];
     char last[LEN];
};
struct guy {                     // 第2个结构
     struct names handle;        // 嵌套结构
     char favfood[LEN];
     char job[LEN];
     float income;
};
int main(void)
{
     struct guy fellow = {        // 初始化一个结构变量
               { "Ewen", "Villard" },
               "grilled salmon",
               "personality coach",
               68112.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;
}

下面是该程序的输出:

Dear Ewen,
     Thank you for the wonderful evening, Ewen.
You certainly prove that a personality coach
is a special kind of guy. We must get together
over a delicious grilled salmon and have a few laughs.
                                                  See you soon,
                                                  Shalala

首先,注意如何在结构声明中创建嵌套结构。和声明 int 类型变量一样,进行简单的声明:

struct names handle;

该声明表明 handle 是一个 struct names 类型的变量。当然,文件中也应包含结构 names 的声明。

其次,注意如何访问嵌套结构的成员,这需要使用两次点运算符:

printf("Hello, %s!\n", fellow.handle.first);

从左往右解释 fellow.handle.first

(fellow.handle).first

也就是说,找到 fellow ,然后找到 fellowhandle 的成员,再找到 handlefirst 成员。