結構體成員指針強制類型轉換


學習系統/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 */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM