Linux下C結構體初始化[總結]


1、前言

  今天在公司看一同事寫的代碼,代碼中用到了struct,初始化一個struct用的是亂序格式,如下代碼所示:

typedef struct _data_t { int a; int b; }data_t; data_t data = { .a = 10, .b = 20, };

   通常初始化一個結構體的方式是按序初始化,形如:data_t data={10,20}。感覺很好奇,如是上網百度一下,發現linux下struct初始化可以采用順序和亂序兩種方式,而亂序又有兩種不同的形式。本文總結一下struct兩種初始化方式的優缺點,並給出完整的測試程序。

2、順序初始化

  教科書上講C語言結構體初始化是按照順序方式來講的,沒有涉及到亂序的方式。順序初始化struct必須要按照成員的順序進行,缺一不可,如果結構體比較大,很容易出現錯誤,而且表現形式不直觀,不能一眼看出各個struct各個數據成員的值。

3、亂序初始化

  亂序初始化是C99標准新加的,比較直觀的一種初始化方式。相比順序初始化而言,亂序初始化就如其名,成員可以不按照順序初始化,而且可以只初始化部分成員,擴展性較好。linux內核中采用這種方式初始化struct。

  亂序初始化有兩種方式,一種是用點(.)符號,一種是用冒號(:)。方式1是C99標准,方式2是GCC的擴展,強烈建議使用第一種方式。

4、測試程序

 1 /*********************************  2  * linux下C語言結構體初始化方法  3  * @author Anker @date:2014/02/11  4  * *******************************/
 5 
 6 #include <stdio.h>
 7 
 8 //函數指針
 9 typedef int (*caculate_cb)(int a, int b); 10 //結構體定義
11 typedef struct _oper { 12     int a; 13     int b; 14  caculate_cb cal_func; 15 } oper; 16 //加法函數定義
17 int add(int a, int b) 18 { 19     return (a+b); 20 } 21 
22 int main() 23 { 24     int ret = 0; 25     //順序初始化結構體1
26     oper oper_one = {10, 20, add}; 27     //亂序初始化結構體2
28     oper oper_two = { 29         .b = 30, 30         .a = 20, 31         .cal_func = &add, 32  }; 33     //亂序初始化結構體3
34     oper oper_three = { 35          cal_func:&add, 36          a:40, 37          b:20, 38  }; 39     ret = oper_one.cal_func(oper_one.a, oper_one.b); 40     printf("oper_one caculate: ret = %d\n", ret); 41     ret = oper_two.cal_func(oper_two.a, oper_two.b); 42     printf("oper_two caculate: ret = %d\n", ret); 43     ret = oper_three.cal_func(oper_three.a, oper_three.b); 44     printf("oper_three caculate: ret = %d\n", ret); 45     return 0; 46 }

測試結果如下圖所示:

5、參考資料

http://blog.csdn.net/adaptiver/article/details/7494081


免責聲明!

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



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