主题
嵌套结构
结构里包含结构
结构的成员本身也可以是一个结构——这叫嵌套。现实里这种关系很自然:一个员工有姓名和入职日期,而入职日期本身又由年、月、日组成。把日期做成独立的结构,既能在员工里复用,也能单独使用:
c
#include <stdio.h>
struct Date {
int year;
int month;
int day;
};
struct Employee {
char name[16];
struct Date hire;
};
int main(void)
{
struct Employee e = {"Alice", {2020, 3, 15}};
printf("%s 入职于 %d-%d-%d\n", e.name, e.hire.year, e.hire.month, e.hire.day);
return 0;
}输出:
text
Alice 入职于 2020-3-15struct Employee 的成员 hire 是 struct Date 类型。访问最内层的成员要用链式 .:先 e.hire 取出日期结构,再 .year 取年——合起来就是 e.hire.year。
多层嵌套与计算
嵌套可以有多层。一个矩形由两个点组成,每个点又有 x、y 坐标:
c
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Rect {
struct Point topleft;
struct Point bottomright;
};
int main(void)
{
struct Rect r = {{0, 10}, {20, 0}};
printf("左上 (%d, %d)\n", r.topleft.x, r.topleft.y);
printf("右下 (%d, %d)\n", r.bottomright.x, r.bottomright.y);
int width = r.bottomright.x - r.topleft.x;
int height = r.topleft.y - r.bottomright.y;
printf("宽=%d 高=%d\n", width, height);
return 0;
}输出:
text
左上 (0, 10)
右下 (20, 0)
宽=20 高=10struct Rect 里有两个 struct Point 成员。初始化用两层花括号:{{0, 10}, {20, 0}}——外层对应 topleft 和 bottomright,内层对应各自的 x、y。算宽度用右下角 x 减左上角 x,算高度用左上角 y 减右下角 y。
注:内层花括号可以省略写成
{0, 10, 20, 0},编译器会按成员顺序分配。但保留嵌套花括号更清晰,一眼看出哪几个值属于哪个子结构,不易出错。
指定初始化器用于嵌套
嵌套结构也能用 .成员名 = 的指定初始化器,内层再嵌一层 .成员名 =:
c
#include <stdio.h>
struct Date {
int year;
int month;
int day;
};
struct Event {
char title[32];
struct Date date;
};
int main(void)
{
struct Event ev = {
.title = "会议",
.date = {.year = 2025, .month = 11, .day = 13}
};
printf("%s:%d年%d月%d日\n", ev.title, ev.date.year, ev.date.month, ev.date.day);
return 0;
}输出:
text
会议:2025年11月13日外层 .title = "会议"、.date = {...},内层再 .year = 2025 等。这样写不依赖成员顺序,结构定义后续增删成员时初始化代码不容易错位。
要点
- 结构的成员可以是另一个结构,形成嵌套;用链式
.访问最内层成员,如e.hire.year。 - 嵌套初始化用多层花括号
{{...}, {...}},对应各层子结构,建议保留内层花括号以提升可读性。 - 指定初始化器支持嵌套:外层
.成员 =,内层再.成员 =,不依赖声明顺序。 - 把可复用的子结构(如日期、坐标)单独定义,既清晰又能在多处复用。