结构体成员指针强制类型转换

学习系统/usr/include/sys/queue.h文件时,遇到如下强制类型转换:

结构体成员指针,强制类型可以转换为相应结构体类型,变为指向相应结构体变量的指针。

以TAILQ_LAST为例,做如下分析:

1、(head)->tqh_last

2、(struct headname *) ((head)->tqh_last)

3、( (struct headname *) ((head)->tqh_last) ) -> tqh_last

4、* ( ( (struct headname *) ((head)->tqh_last) ) -> tqh_last )

(注:图片摘自博客http://blog.csdn.net/astrotycoon/article/details/42917367 红色内容与本篇博客相关 )

测试案例:

 1 #include <stdio.h>
 2 struct NodeA {
 3     int a;
 4     int b;
 5 };
 6 struct NodeB {
 7     int c;
 8     int d;
 9 };
10 
11 int main(int argc, char *argv[])
12 {
13     struct NodeA a1;
14     struct NodeB b1;
15 
16     a1.a = 1;
17     a1.b = 2;
18     b1.c = 3;
19     b1.d = 4;
20 
21     int *p = &(b1.c);
22     printf("%d\n", *p);
23     printf("%d\n", ((struct NodeA *) p) -> a);
24     printf("%d\n", ((struct NodeA *) p) -> b);
25     return 0;
26 }
27 /*
28 输出结果:
29 3
30 3
31 4
32 */

 

 1 #include <stdio.h>
 2 struct Node {
 3     int a;
 4     int b;
 5 };
 6 
 7 int main(int argc, char *argv[])
 8 {
 9     struct Node a1;
10 
11     a1.a = 1;
12     a1.b = 2;
13 
14     int *p = &(a1.a);
15     printf("%d\n", *p);
16     printf("%d\n", ((struct Node *) p) -> a);
17     printf("%d\n", ((struct Node *) p) -> b);
18     return 0;
19 }
20 /*
21 1
22 1
23 2
24 */

 

posted @ 2017-12-26 15:59  suphgmhh  阅读(2850)  评论(0编辑  收藏  举报