// 僅定義類型,不配置記憶體
struct student {
int num;
char name[20];
};
struct student stu;
printf("struct size: %lu\n", sizeof(stu)); // 24
printf("int size: %lu\n", sizeof(int)); // 4
printf("char[20] size: %lu\n", sizeof(char[20])); // 20
4 + 20 = 24,符合預期。
char sexstruct student {
int num; // 4 bytes
char sex; // 1 byte
char name[20]; // 20 bytes
};
sizeof(stu) = 28 // 而非 4+1+20=25
原因:編譯器按 4 位元組對齊。sex 後需填充 3 位元組,使 name 起始位址為 4 的倍數。
struct student {
char name[23]; // 23 bytes
int num; // 4 bytes
char sex; // 1 byte
};
sizeof = 32 // 23 -> 對齊到 24, +4 = 28, +1 -> 對齊到 32
結構體總大小必須是最大成員大小的整數倍(此處為 4),方便陣列存取。
struct student_opt {
int num; // 4
char sex; // 1
char name[20]; // 20
// 共 24,sex 緊湊在 num 後,name 自然對齊
};
將大型別、對齊要求高的成員放前面,小型別放中間或利用空隙,可減少填充位元組。
union data {
int i;
float f;
char str[20];
};
i 後讀取 f 為未定義行為(除非用於型別雙關)。offsetof 宏檢查成員偏移:offsetof(struct student, name)。#pragma pack(n) 或 GCC __attribute__((packed)),但可能降低存取效能。struct packet {
int type; // 0=int, 1=float, 2=string
union data payload;
};
理解記憶體對齊與聯合體特性,是編寫高效、可移植 C 程式的關鍵進階技能。