结构体的自引用(self reference),就是在结构体内部,包含指向自身类型结构体的指针。
结构体的相互引用(mutual reference),就是说在多个结构体中,都包含指向其他结构体的指针。
1. 自引用 结构体
1.1 不使用typedef时
错误的方式:
- struct tag_1{
- struct tag_1 A; /* 结构体 */
- int value;
- };
这种声明是错误的,因为这种声明实际上是一个无限循环,成员b是一个结构体,b的内部还会有成员是结构体,依次下去,无线循环。在分配内存的时候,由于无限嵌套,也无法确定这个结构体的长度,所以这种方式是非法的。
正确的方式: (使用指针):
- struct tag_1{
- struct tag_1 *A; /* 指针 */
- int value;
- };
由于指针的长度是确定的(在32位机器上指针长度为4),所以编译器能够确定该结构体的长度。
1.2 使用typedef 时
错误的方式:
- typedef struct {
- int value;
- NODE *link; /* 虽然也使用指针,但这里的问题是:NODE尚未被定义 */
- } NODE;
这里的目的是使用typedef为结构体创建一个别名NODEP。但是这里是错误的,因为类型名的作用域是从语句的结尾开始,而在结构体内部是不能使用的,因为还没定义。
正确的方式:有三种,差别不大,使用哪种都可以。
- /* 方法一 */
- typedef struct tag_1{
- int value;
- struct tag_1 *link;
- } NODE;
- /* 方法二 */
- struct tag_2;
- typedef struct tag_2 NODE;
- struct tag_2{
- int value;
- NODE *link;
- };
- /* 方法三 */
- struct tag_3{
- int value;
- struct tag *link;
- };
- typedef struct tag_3 NODE;
2. 相互引用 结构体
错误的方式:
- typedef struct tag_a{
- int value;
- B *bp; /* 类型B还没有被定义 */
- } A;
- typedef struct tag_b{
- int value;
- A *ap;
- } B;
错误的原因和上面一样,这里类型B在定义之 前 就被使用。
正确的方式:(使用“不完全声明”)
- /* 方法一 */
- struct tag_a{
- struct tag_b *bp; /* 这里struct tag_b 还没有定义,但编译器可以接受 */
- int value;
- };
- struct tag_b{
- struct tag_a *ap;
- int value;
- };
- typedef struct tag_a A;
- typedef struct tag_b B;
- /* 方法二 */
- struct tag_a; /* 使用结构体的不完整声明(incomplete declaration) */
- struct tag_b;
- typedef struct tag_a A;
- typedef struct tag_b B;
- struct tag_a{
- struct tag_b *bp; /* 这里struct tag_b 还没有定义,但编译器可以接受 */
- int value;
- };
- struct tag_b{
- struct tag_a *ap;
- int value;
- };
/*以下为自引用程序,VC6.0编译通过*/
#include <stdio.h>
typedef struct student_tag //student是标识符,stu_type是类型符号,struct student=stu_type
{
int num; /*定义成员变量学号*/
int age; /*定义成员变量年龄*/
struct student_tag* stu_point;
}stu_type;
void main()
{
/*给结构体变量赋值*/
//struct student stu ={001,"lemon",'F',23,95};
stu_type stu ={001,26,&stu};
printf("学生信息如下:\n"); /*输出学生信息*/
printf("学号:%d\n",stu.num); /*输出学号*/
printf("年龄:%d\n",stu.age); /*输出年龄*/
printf("%p\n",stu.stu_point); /*指针变量的值,为四个字节*/
printf("%d\n",sizeof(stu)); /*结构体类型stu_type占了12个字节*/
}
/*下面为程序运行结果*/
/*以下为互引用程序,使用结构体的不完整声明(incomplete declaration)*/
#include <stdio.h>
struct teacher; //此条语句可省去
struct student
{
int stu_num;
struct teacher* tea_point;/* struct teacher省去的话,编译器也可以接受 */
};
struct teacher
{
int tea_num;
struct student* stu_point;
};
typedef struct student stu_type;
typedef struct teacher tea_type;
void main()
{
tea_type tea1={000,NULL};
stu_type stu1={005,NULL};
stu1.stu_num=001;
stu1.tea_point=&tea1;
tea1.tea_num=002;
tea1.stu_point=&stu1;
printf("%d \n",(stu1.tea_point)->tea_num);
printf("%p \n",(stu1.tea_point)->stu_point);
printf("%d \n",(tea1.stu_point)->stu_num);
printf("%p \n",(tea1.stu_point)->tea_point);
}
/*下面为程序运行结果*/