結構體定義 typedef struct 用法

2021-07-07 01:15:47 字數 859 閱讀 4898

typedef是型別定義的意思。typedef struct 是為了使用這個結構體方便。

具體區別在於:

若struct node這樣來定義結構體的話。在定義 node 的結構體變數時,需要這樣寫:struct node n;

若用typedef,可以這樣寫:typedef struct node{}node; 。在申請變數時就可以這樣寫:node n;其實就相當於 node 是node 的別名。區別就在於使用時,是否可以省去struct這個關鍵字。

1 首先:

在c中定義乙個結構體型別時如果要用typedef:

typedef struct student

stu,student;

於是在宣告變數的時候就可:stu stu1;或者:student stu2;(stu 和student 同時為student的別名)

如果沒有typedef即:

struct student

stu;

就必須用struct student stu1;或者struct stu stu1;來宣告

另外這裡也可以不寫student(於是也不能struct student stu1;了)

typedef struct

stu;

2其次:

在c++中如果用typedef的話,又會造成區別:

struct student

stu1;//stu1是乙個變數

typedef struct student2

stu2;//stu2是乙個結構體型別,即stu2是student2的別名

使用時可以直接訪問stu1.no

但是stu2則必須先定義 stu2 s2;

然後 s2.no=10;

結構體定義

struct在c語言中是乙個關鍵字,用於定義結構資料型別。問題中的兩種定義的區別在於第一種是給student資料型別,重新定義了乙個型別別名,而第二種則單純的表示一種叫做student的資料結構型別。兩者的主要區別在於後面直接定義變數時。如下 則可以直接在結構體後面定義乙個zhang san的結構體...

結構體定義 方法

include include struct student s3 定義方式3,不常用的一種方式 intmain 定義方式2,最方便的一種方式 s3.id 3 定義方式3 strcpy s3.name,wang s3.age 22 struct student ps2 s2 定義指向s2的指標 pr...

結構體的定義

關於c語言中結構體的幾種定義方式和它們之間的不同。1 先定義結構體型別,再定義結構體型別變數 struct 結構體名稱 struct 結構體名稱 結構體變數1,結構體變數2 struct 結構體名稱 結構體變數3,結構體變數4 用此結構體型別,可以定義更多的該結構體型別變數。2 定義結構體型別同時定...