C语言之玩转结构体3 |
您所在的位置:网站首页 › qq互赞有什么用处 › C语言之玩转结构体3 |
本节我们来介绍结构体的自引用和互引用: 结构体的自引用就是指在结构体内部,包含指向自身类型结构体的指针。 结构体的互引用就是指在结构体中,包含指向其他结构体的指针。 二、结构体的自引用不用typedef,代码如下: #include "stdio.h" struct _student_t { struct _student_t *a; short b; int value; }; int main(void) { struct _student_t c; printf("len = %d",sizeof(c)); }运行: 切记,结构体自引用,成员定义只能是指针,如果结构体内成员定义为struct _student_t a; 则会报错,因为a定义中又有a,无限循环,系统无法确定该结构体的长度,会判定定义非法。 使用typedef,代码如下: #include "stdio.h" typedef struct _student_t { struct _student_t *a; short b; int value; }student_t; int main(void) { student_t c; printf("len = %d",sizeof(c)); }使用typedef时,如果自引用的话,需要带上标签 "struct _student_t “,如果定义成员直接使用"student_t” 则会报错,因为在结构体内部定义结构体变量时,它会去找这个结构体,但该结构体还未声明完成,所以无法被引用和定义。 #include "stdio.h" struct _student2_t; //不完全声明 struct _student1_t { struct _student2_t *a; short b; int value; }; struct _student2_t { struct _student1_t *a; short b; int value; }; int main(void) { struct _student2_t c; struct _student1_t d; printf("len = %d,%d",sizeof(c),sizeof(d)); } 三、结构体的互引用这里其实我们和自引用一样,注意两点即可。 1:结构体中定义结构体成员一定要注意,不能有像自引用那样的“无限嵌套”情况发生。 2:定义结构体中的结构体变量时,要注意该结构体已经先声明好,之后才可以定义。 对于2的声明,我们可以使用“不完全声明”来实现。 这里因为在struct _student1_t结构体中,定义a结构体变量,而该结构体a在此前还未声明好,因此定义是非法的,我们加上struct _student2_t这个声明,即可定义。 不过笔者在c-free和vc++ 6.0中测试,注释掉不完全声明,不会报错。其他平台待测试,大家可以试试,为了保险,我们实际用的话尽量还是加上为好。 四、结语如您在使用过程中有任何问题,请加QQ群进一步交流。 QQ交流群:906015840 (备注:物联网项目交流)。 获取资料:微信扫描下方二维码,关注公众号:一个物联网项目的前世今生。 静晨出品:静之所想,晨之所计 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |