結構體和共用體

2021-09-29 03:23:26 字數 3175 閱讀 8092

宣告結構和結構體變數

#include#include#define maxtitl 41

#define maxautl 31

#define max 100

/*結構宣告:並未建立實際的資料物件:也稱結構宣告為模板*/

struct bookbok;

int main()

復合字面常量

bk1=(struct book);

伸縮陣列成員

struct flex;  

struct flex *pf1,*pf2;

*pf2=*pf1

//1,不能用帶伸縮型陣列成員的結構進行賦值或拷貝:這樣只能拷貝除伸縮型陣列成員以外的其他成員

//2,不能以按值方式把這種結構傳遞給結構。要把結構的位址傳遞給函式

//3.不要使用帶伸縮型陣列成員的結構作為陣列成員或另乙個結構成員

}

初始化

#includestruct studentstudent1=;

int main()

; printf("第乙個學生:\n");

printf("名字:%s\n",student1.st_name);

printf("性別:%c\n",student1.st_***);

printf("年級:%d\n",student1.st_grade);

printf("第二個學生:\n");

printf("名字:%s\n",student2.st_name);

printf("性別:%c\n",student2.st_***);

printf("年級:%d\n",student2.st_grade);

struct student student3=; //指定初始化器

}

結構體陣列定義及初始化

#includestruct studentstudent[5]=,

, , ,

};int main()

return 0;

}

結構體指標

/*

*/#include#includestruct studentstudent1;

int main()

指向結構體陣列的指標

#includestruct studentstudent[5]=,

, , ,

};int main()

return 0;

}

包含結構的結構

#includestruct date;

struct stuentstudent=};

int main()

使用結構體變數作為函式的引數

使用結構體變數作為函式實引數時,採取的是「值傳遞」方式,即會將結構體變數所佔記憶體單元的內容全部順序出傳遞給形參,

形參也必須是同型別的結構體變數。

注:在形參位置使用結構體變數,但是在函式呼叫期間,形參也要占用記憶體單元。這種傳遞方式在空間和時間上開銷比較大,

另外,如果在函式與內部修改了變數中成員的值,則改變的值不會返回到主調函式中

#include#includestruct studentstudent=;

void display(struct student stu);

int main()

void display(struct student stu)

使用指向結構體變數的指標作為函式的引數

在傳遞結構體變數的指標時,只是將結構體變數的首位址進行傳遞,並沒有將變數的副本進行傳遞。

注:因為傳遞的是變數的位址,如果在函式中改變成員中資料看,那麼返回主調函式的變數會發生變化

#include#includestruct studentstudent=;

void display(struct student *stu); //宣告結構同時定義變數

int main()

void display(struct student *stu)

定義共用體型別的一般形式:

union 共用體名

變數列表;

1.記憶體段可以用來存放幾種不同型別的成員,但是每次只能存放其中的一種,而不能同時存放所有的型別。

也就是說,在共用體中,只有乙個成員起作用,其他成員不起作用

2.共用體變數中起作用的成員是最後一次存放的成員。在存入乙個新的成員後,原有的成員失去作用。

3.共用體變數的位址和他的各成員的位址是一樣的。

4.不能對共用體變數名賦值,也不能企圖引用變數名來得到乙個值

#includeunion dataunionvariable;

int main()

; //對共用體初始化時,只需要乙個初始化值就足夠了,其型別必須和共用體的第乙個成員一致

printf("a=%d\n",un.a);

printf("c=%c\n",un.c);

un.c='a';

printf("a=%d\n",un.a);

printf("c=%c\n",un.c);

return 0;

}

乙個列舉變數包含一組相關的識別符號,其中每個識別符號都對應乙個整數值,稱為列舉常量

#includeenum colorcolor;			//定義列舉變數,並初始化

int main()

return 0;

}

共用體和結構體

共用體和結構體的宣告與初始化的格式不同。宣告 struct or union new st 初始化 new st 和陣列一樣,使用逗號分隔,並用花括號括起。也可以全放在一行。可以同時完成定義結構和建立結構變數的工作,只需要將變數名放在結束括號的後面 struct or union new st ne...

結構體和共用體

通過前面的講解,我們知道結構體 struct 是一種構造型別或複雜型別,它可以包含多個型別不同的成員。在c語言中,還有另外一種和結構體非常類似的語法,叫做共用體 union 它的定義格式為 union 共用體名 共用體有時也被稱為聯合或者聯合體,這也是 union 這個單詞的本意。結構體和共用體的區...

結構體 共用體

結構體 結構體的定義1 struct mystruct 定義新變數 struct mystruct s1 結構體定義2 typedef struct mystruct mstrct 定義新變數 mstrct s1 結構體定義3 type struct mstrct 定義新變數 mstrct s1 共...