struct & typedef struct
基本上我們會這樣使用 struct
struct {
...
} p1, p2;
此時, p1,p2 這兩個變數是隸屬於 struct {...} 型態的變數。
但是遇到以下需要分開 p1, p2 變數做宣告時,就必須得:
struct {
...
} p1;
/* 一堆程式碼 */
struct {
...
} p2;
我們需要重複打兩次 struct {...} 的內容,非常之冗;所以於是有了第二種方式:
struct p_type {
...
};
struct p_type p1;
struct p_type p2;
在 struct 後面加上 tag name,也就是那個 p_type,就可以不用重複打同樣的 struct 結構。
這時,我們有第三種方式可以少打 struct 這個字,就是使用 typedef:
typedef struct {
...
} PType;
PType p1;
PType p2;
你會發現到 typedef 會將 struct {...} 以別名(Alias)Ptype 取而代之;之後 Ptype 就是代表 struct {...} 的代名詞。
有一個地方大家可能都會搞混:
typedef struct PType { // 第一個 PType
...
} PType; // 第二個 PType
PType p1;
PType p2;
這裡的 PType p1; 與 PType p2; 是哪一個 PType 發揮效果了呢?答案是第二個 PType;因為 typedef 會將 struct PType {...} 以別名 PType(第二個的)取而代之。
另外一個例子:
typedef struct PType_tag {
...
} PType_alias;
struct PType_tag p1;
PType_alias p2;
這樣有清楚ㄌ嗎
Share this post
Twitter
Google+
Facebook
Reddit
LinkedIn
Pinterest
Email