C 嵌套结构
嵌套结构
一个结构体也可以包含另一个结构体作为成员。这称为嵌套结构,当您想要将相关数据分层分组时,嵌套结构非常有用。
示例
#include <stdio.h>
struct Owner {
char firstName[30];
char lastName[30];
};
struct Car {
char brand[30];
int year;
struct Owner owner; // Nested structure
};
int main() {
struct Owner person = {"John", "Doe"};
struct Car car1 = {"Toyota", 2010, person};
printf("Car: %s (%d)
", car1.brand, car1.year);
printf("Owner: %s %s
", car1.owner.firstName, car1.owner.lastName);
return 0;
}
亲自试一试 »
这里,Car 结构内部包含另一个结构 (Owner)。这样就很容易组织复杂的数据,例如汽车及其车主。

