struct 和typedef struct


1.typedef

(1)typedef的使用

定義一種類型的別名,而不只是簡單的宏替換(見陷阱一)。用作同時聲明指針型的多個對象

typedef char* PCHAR; // 一般用大寫,為char*起個別名PCHAR
PCHAR pa, pb; // 可同時聲明了兩個指向字符變量的指針,若是char* a,b則不行,只是聲明了一個指針a,一個字符b
typedef struct node NODE;//struct node = NODE,eg:struct node n; <==> NODE n;其中n為node型非指針變量
typedef struct node* PNODE//struct node* = PNODE,eg:struct node* a; <==>  PNODE a;其中a為node型指針變量
typedef struct NODE;//不能這樣定義,報錯缺變量

 

(2)typedef兩大陷阱

陷阱一:

typedef定義了一種類型的新別名,不同於宏,它不是簡單的字符串替換。比如:
先定義:
typedef char* PSTR;
然后:
int mystrcmp(const PSTR, const PSTR);

const PSTR實際上相當於const char*嗎?不是的,它實際上相當於char* const。
原因在於const給予了整個指針本身以常量性,也就是形成了常量指針char* const。
簡單來說,記住當const和typedef一起出現時,typedef不會是簡單的字符串替換就行。

陷阱二:

typedef在語法上是一個存儲類的關鍵字(如auto、extern、mutable、static、register等一樣),雖然它並不真正影響對象的存儲特性,如:
typedef static int INT2; //不可行
編譯將失敗,會提示“指定了一個以上的存儲類”。

以上資料出自: http://blog.sina.com.cn/s/blog_4826f7970100074k.html 

2.C++定義結構體的幾種方式

(1)非指針型結構體

struct Seqlist{//C++標准定義結構體方法
    int elem[MAX];//數組
    int len;//數組長
};

typedef struct SS{
    int elem[MAX];//數組
    int len;//數組長
}Seqlist;//為結構體SS起一個別名Seqlist

typedef struct{
    int elem[MAX];//數組
    int len;//數組長
}Seqlist;//定義匿名結構體,別名為Seqlist

(2)指針型結構體(兩種定義二叉樹的方法,第一種為規范方法)

struct BinTNode{ //定義結點
    char data;
    struct BinTNode *lchild, *rchild;//經測試,在vc6.0中去掉struct也行
};
typedef BinTNode *BinTree; //定義二叉樹,本質是結構體指針或節點指針

typedef struct node{ //定義結點
    char data;
    struct node *lchild, *rchild;
}BinTNode,*BinTree; //定義二叉樹

 

3.C語言中結構體定義

https://www.cnblogs.com/qyaizs/articles/2039101.html

 


免責聲明!

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



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