復合資料型別

2021-07-15 13:01:04 字數 3105 閱讀 5287

一.struct結構體(封裝資料、存放多種不同的資料型別)

struct的宣告放在全域性區

1.       宣告和定義

宣告:

struct student

;struct student stu_array[3] =

, ,

};int i;

for(i = 0; i < 3; i++)

for(i = 0; i < 3; i++)

#include

struct student

;int main()

sizeof(stu) = 12;//字對齊

struct student

;sizeof(stu) = 16;//字對齊,記憶體空洞

struct student

;sizeof(stu) = 6;//半字對齊

struct student

;sizeof(stu) = 36;

定義:struct student stu;

2.       初始化(結構體變數用「.」訪問,結構體指標用「->」訪問)

1)  struct student stu = ;

2)  struct student stu =

;3)  struct student

;stu.name = (char *)malloc(sizeof(char) * 100);

scanf("%s", stu.name);

//structstudent *p_stu = &stu;//p_stu == &stu;*p_stu== stu;

//scanf("%s", p_stu.name);

4)  stu.id = 1;

(*p_stu).id = 1;

p_stu->id = 1;

(&stu)->id = 1;

scanf("%d", &stu.id);

scanf("%d", &(p_stu.id));

5)        stu.name = 「zhangsan」;//此種寫法錯誤,陣列名為指標常量,不可以直接使用。

strcpy(stu.name, 「zhangsan」);

strcpy(p_stu->name, 「zhangsan」);

3.       結構體陣列

struct student stu_array[3] = ,,

};int i;

for(i = 0; i < 3; i++)

for(i = 0; i < 3; i++)

4.       使用注意事項宣告struct結構體時,相同資料型別放在一起,防止記憶體空洞。

例項:

#include 

struct student

;int main()

sizeof(stu) = 12;//字對齊

struct student

;sizeof(stu) = 16;//字對齊,記憶體空洞

struct student

;sizeof(stu) = 6;//半字對齊

struct student

;sizeof(stu) = 36;

5.       作用利用結構體封裝返回多個值

封裝函式的形參

二.union共用體(和struct類似)

1.       宣告

union node

;2.       定義

union node p;

union node * pp = &p;

3.       初始化

p.num = 1;

pp->num = 1;

p.ch = 『a』;

4.       注意事項

共用體與結構體的區別在於:共用體是共用一塊記憶體空間,會發生值覆蓋的情況。

例如:p.num = 1;

p.ch = 『a』;

printf(「%d\n」, p.num);

此時輸出的值為97,發生了值覆蓋。

5.       大端位元組序&小端位元組序(cpu的屬性)

(無論大端還是小端都是從低位址開始存放)

判斷cpu是小端位元組序還是大端位元組序的方法

1).共用體

#include 

union node;

int main()

else

return 0;

}

2).指標

#include 

union node;

int main()

else

return0;

}#include

enum node;

int main()

三.enum列舉(相當於整型)

#include 

union node;

int main()

else

return0;

}#include

enum node;

int main()

列舉相當於整數巨集,提高**可讀性(杜絕幻數)

復合資料型別

復合資料型別 作用 封裝資料 多種不同型別資料存放在一起 應存放在全域性,在訪問結構體中的變數時,應用stu.id stu.name 初始化的方式 在對陣列進行初始化時 strcpy stu.name,zhangsan 在對指標進行初始化時 char name 對name進行初始化 stu.name...

復合資料型別

結構體 作用 封裝資料 把多種不同的資料型別放在一起 注意 一般放在全域性 分號不能省略。結構體變數用點訪問 結構體指標用 訪問 初始化 靜態初始化 動態初始化 使用注意事項 給結構體中的陣列成員賦值時,不能直接將字串賦給陣列名,可以使用strcpy函式 給結構體中的指標變數成員賦值時,要先給指標分...

復合資料型別

include 結構體 struct student1 s4 無名結構體 struct s2,s3 int main 使用,變數用 引用成員,指標用 引用成員 printf id d,name s n s5.id,s5.name struct student1 ps s4 s4.id 20 prin...