C 構造型別 陣列、列舉、聯合體、結構體(位段) 位元組對齊 和 大小端儲存
列舉
- .列舉:被命名的標籤常量(對事物的列出)
---型別的構造------- enum key{ UP, //成員<標籤常量:預設第一個為0 後一個總是前一個的值加一> DOWN, LEFT, RIGHT=100, //後面的標籤常量加一 UNKNOW, };
enum key yy;宣告列舉變數
UP=140; error 成員為標籤常量 不可改變
yy=UP;
可以賦某個成員 也可以直接當作整變數型用 -----------------------//////匿名列舉////////// enum{ blue, red, black, white, };
聯合體
聯合體(共用體):所有成員共用同一段空間
union tt{ int value; char ch; float f; };
union tt temp;//宣告變數 temp.value=55;//聯合體變數通過'.'訪問成員 聯合體指標通過'->'訪問成員
性質:1.該聯合體空間到小至少要為最大成員空間大小 2.成員同一時刻不能同時使用 3.定義時總是以第一個成員型別初始化
結構體
student:型別名 struct student{ int id; //成員 char name[32]; float math,chinese; };
宣告變數struct student tom
typedef struct student Student_t; Student_t king;
tom.id=10;結構變數通過"."訪問結構體成員 struct student *ptr=&tom; ptr->id;結構指標通過"->"訪問結構體成員
匿名結構 struct{ float weight; float age; };
匿名結構:只有同時宣告的變數才可視為同類型考慮到結構為較大的資料型別,傳參習慣傳其地址,提高傳參效率!!!!!!!
位段: 把一個或N個整型空間分給若干成員使用,成員可以使用其中某幾個bit
struct tt{ int a:2; unsigned int temp:2; //float ff:3; 不可為非整型成員 short ss:3; int :7; //跳過該7個bit不使用 int b:5; int c:10; int d:20; };
結構體注意點
struct student{ int id,age; //成員 char name[32]; float math; float chinese; };
struct student *p;
struct student one={1,20,"king",55.6,85.5}; //定義:依次初始化
struct student one={1,}; //定義:未定義的成員值為0 struct student one={1,.math=88.8,55.6}; //定義:c99指定成員賦值
//p->name="KING"; //陣列不支援整體賦值 strcpy(p->name,"KING");
struct student other;
//other={3,25,"king",100,80}; //error 僅在定義時可以用"{}"直接初始化
other=one; //同類型的結構體可以直間賦值
other=(struct student){3,25,"king",100,80}; //原理:同類型的結構體可以直接賦值
#include <stdio.h> struct aa{ int array[5]; }; int main(void) { struct aa temp={11,22,33,44,55}; int i; for(i=0;i<5;i++) { printf("%d ",temp.array[i]); } putchar('\n'); struct aa other; other=temp; for(i=0;i<5;i++) { printf("%d ",other.array[i]); } putchar('\n'); return 0; }
位元組對齊
-----------------------------------------------------位元組對齊:結構或聯合的成員處於特定的地址
1.每個成員要在能被其空間大小整除的地址 2.整體結構大小要為最大成員空間大小的整數倍
3.如果成員空間大小大於平臺對齊位元組大小,則按平臺對齊位元組大小算 如:某平臺以4位元組對齊 那麼double成員只需要在被4整除的地址即可 整體空間也只需4的整數倍
設定為4位元組對齊 #pragma pack(4)
取消位元組對齊:<在用網路傳送結構,用結構讀檔案格式頭,用結構作協議要取消位元組對齊> #pragma pack(1)
恢復預設位元組對齊 #pragma pack()
大小端儲存
大小端 : 大於一個位元組的資料由於不同CPU特性儲存分為大端儲存和小端儲存
小端儲存: 低資料位儲存在低位元組(地址) 高資料位儲存在高位元組(地址) 大端儲存: 低資料位儲存在高位元組(地址) 高資料位儲存在低位元組(地址)