結構體是 C 語言構建複雜資料類型的核心機制,將不同型別資料封裝為單一實體。本文涵蓋定義語法、嵌套結構、指標操作、typedef 簡化與記憶體佈局細節。
struct Fish {
const char *name;
const char *species;
int teeth;
int age;
};
void catalog(struct Fish f) {
printf("%s is a %s with %i teeth. Age: %i\n",
f.name, f.species, f.teeth, f.age);
}
int main() {
struct Fish snappy = {"Snappy", "Piranha", 69, 4};
catalog(snappy);
return 0;
}
值傳遞語意:結構體賦值/傳參預設為淺拷貝(逐成員複製)。若含指標成員,僅複製指標值,不複製指向資料。
struct Preferences {
const char *food;
float exercise_hours;
};
struct Fish {
const char *name;
const char *species;
int teeth;
int age;
struct Preferences care; // 嵌套
};
struct Fish snappy = {
"Snappy", "Piranha", 69, 4,
{"Meat", 7.5} // 嵌套初始化
};
printf("%s likes %s\n", snappy.name, snappy.care.food);
// 命名結構體
typedef struct CellPhone {
int cell_no;
const char *wallpaper;
} Phone; // Phone 為型別別名
// 匿名結構體(現代 C 常用)
typedef struct {
int cell_no;
const char *wallpaper;
} Phone;
使用 Phone p = {5555, "sinatra.png"}; 直接建立變數,無需 struct 關鍵字。
Phone p = {5555, "sinatra.png"};
Phone *ptr = &p;
// 兩種等價存取方式
(*ptr).cell_no = 6666; // 需括號,優先級高於 .
ptr->cell_no = 6666; // 箭頭運算子,語法糖,推薦使用
// 常見錯誤
// *ptr.cell_no // 錯誤!解析為 *(ptr.cell_no),ptr 無成員 cell_no
struct Example {
char c; // 1 byte
// 3 bytes padding
int i; // 4 bytes
char c2; // 1 byte
// 3 bytes padding
}; // 總計 12 bytes (非 1+4+1=6)
int 需 4 位元組對齊)#pragma pack(n) 可調整對齊界限,但可能影響存取效能struct Buffer {
size_t len;
char data[]; // 不佔大小,必須為最後一個成員
};
struct Buffer *buf = malloc(sizeof(struct Buffer) + 100);
buf->len = 100; // 動態分配可變長度資料
typedef 隱藏 struct 關鍵字const struct Type * 避免拷貝開銷free).member = value (C99),順序無關、可讀性強