详解C语言中结构体的自引用和相互引用

时间:2021-05-02

结构体的自引用(self reference),就是在结构体内部,包含指向自身类型结构体的指针。
结构体的相互引用(mutual reference),就是说在多个结构体中,都包含指向其他结构体的指针。
1. 自引用 结构体
1.1 不使用typedef时

错误的方式:

? 1 2 3 4 struct tag_1{ struct tag_1 A; int value; };

这种声明是错误的,因为这种声明实际上是一个无限循环,成员b是一个结构体,b的内部还会有成员是结构体,依次下去,无线循环。在分配内存的时候,由于无限嵌套,也无法确定这个结构体的长度,所以这种方式是非法的。
正确的方式: (使用指针):

? 1 2 3 4 struct tag_1{ struct tag_1 *A; int value; };

由于指针的长度是确定的(在32位机器上指针长度为4),所以编译器能够确定该结构体的长度。
1.2 使用typedef 时
错误的方式:

? 1 2 3 4 typedef struct { int value; NODE *link; } NODE;

这里的目的是使用typedef为结构体创建一个别名NODEP。但是这里是错误的,因为类型名的作用域是从语句的结尾开始,而在结构体内部是不能使用的,因为还没定义。
正确的方式:有三种,差别不大,使用哪种都可以。

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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. 相互引用 结构体
错误的方式:

? 1 2 3 4 5 6 7 8 9 typedef struct tag_a{ int value; B *bp; } A; typedef struct tag_b{ int value; A *ap; } B;


错误的原因和上面一样,这里类型B在定义之 前 就被使用。
正确的方式:(使用“不完全声明”)

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 struct tag_a{ struct tag_b *bp; int value; }; struct tag_b{ struct tag_a *ap; int value; }; typedef struct tag_a A; typedef struct tag_b B; struct tag_a; struct tag_b; typedef struct tag_a A; typedef struct tag_b B; struct tag_a{ struct tag_b *bp; int value; }; struct tag_b{ struct tag_a *ap; int value; };

3.实例:
应用结构体指针变量,打印结构体成员变量的信息。

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include <stdio.h> struct Point { double x; double y; double z; }; int main() { struct Point oPoint1={100,100,0}; struct Point oPoint2; struct Point *pPoint; pPoint=& oPoint2;   (*pPoint).x= oPoint1.x; (*pPoint).y= oPoint1.y; (*pPoint).z= oPoint1.z; printf("oPoint2={%7.2f,%7.2f,%7.2f}",oPoint2.x, oPoint2.y, oPoint2.z); return(0); }

程序运行结果如下:

? 1 oPoint2={ 100.00,100.00,0.00}

其中表达式&oPoint2的作用是获得结构体变量oPoint2的地址。表达式pPoint=&oPoint2的作用是将oPoint2的地址存储在结构体指针变量pPoint中,因此pPoint存储了oPoint2的地址。*pPoint代表指针变量pPoint中的内容,因此*pPoint 和oPoint2等价。
通过结构体指针变量获得其结构体变量的成员变量的一般形式如下:
(*结构体指针变量). 成员变量
其中“结构体指针变量”为结构体指针变量,“成员变量”为结构体成员变量名称,“.”为取结构体成员变量的运算符。
另外C语言中引入了新的运算符“->”,通过结构体指针变量直接获得结构体变量的成员变量,一般形式如下:
结构体指针变量-> 成员变量
其中“结构体指针变量”为结构体指针变量,“成员变量”为结构体成员变量名称,“- >”为运算符。
因此,例中的部分代码

? 1 2 3 4 5 …… (*pPoint).x= oPoint1.x; (*pPoint).y= oPoint1.y; (*pPoint).z= oPoint1.z; ……

等价于

? 1 2 3 4 5 …… pPoint->x= oPoint1.x; pPoint->y= oPoint1.y; pPoint->z= oPoint1.z; ……

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章