文章目录
一、结构体的自引用
1.结构体内不能包含同类型的结构体变量
//错误写法
struct Student
{
char name[20];
struct Student s1;
};
这种写法是非法的,原因是,结构体内的成员 s1 是另一个结构体,它的类型是 struct Student,但这个类型又包含同类型的结构体变量,这样就会一直重复下去
2.使用结构体指针来实现自引用
//结构体自引用的正确写法
struct Student
{
char name[20];
struct Student* next;//结构体指针,指向另一个结构体;指针的长度是确定的
};
3.有 typedef 的自引用
typedef 重命名后的别名在结构体里面不能直接用
/* 正确写法 */
typedef struct Student
{
char name[20];
struct Student* next;
}Stu;
/* 错误写法 */
typedef struct Student
{
char name[20];
Stu* next;
}Stu;
同时要注意匿名定义结构体类型时自引用是不可行的
//自引用不可行
typedef struct
{
char name[20];
Stu* next;
}Stu;
原因是创建成员 next(类型为Stu的结构体变量)时,结构体类型 Stu 尚未被定义
二、结构体嵌套初始化
1.结构体嵌套
struct Student
{
char name[20];
int age;
};
struct teacher
{
char name[20];
struct Student s1;
int age;
};
2.结构体嵌套初始化
struct Student
{
char name[20];
int age;
};
struct teacher
{
char name[20];
struct Student st;//教师结构体包含学生结构体
int age;
};
int main()
{
//初始化
struct teacher t1 = { "teacher_Jack",{"Student_Pit",20},30 };
//访问
printf("%s %s %d %d\n", t1.name, t1.s1.name, t1.s1.age, t1.age);
return 0;
};
三、两个结构体互相包含
如果两个结构体互相包含,则需要对其中一个结构体进行不完整声明
struct B; //对结构体B进行不完整声明
//结构体A中包含指向结构体B的指针
struct A
{
struct B *pb;
//other members;
};
//结构体B中包含指向结构体A的指针,在A声明完后,B也随之进行声明
struct B
{
struct A *pa;
//other members;
};