結構體(struct)是 C 語言實現使用者自訂型別的核心機制,允許將不同型別的資料封裝為單一邏輯單元。本文系統整理結構體宣告、變數定義、初始化、成員存取、指標操作、賦值規則與記憶體配置細節。
struct point {
double x, y;
};
struct point 為型別名稱(標籤),等同於 int、double 等內建型別struct point { double x, y; };
struct point p1, p2; // 使用標籤定義變數
struct point {
double x, y;
} p1, p2; // 直接定義變數
struct {
double x, y;
} p1, p2; // 僅能定義這兩個變數,無法後續復用型別
// 定義時初始化
struct point p = { 1.0, 2.0 };
// 指定初始化器(C99)
struct point p = { .y = 2.0, .x = 1.0 };
// 部分初始化:未指定成員自動歸零
struct point p = { .x = 1.0 }; // y = 0.0
| 語法 | 適用對象 | 範例 |
|---|---|---|
. | 結構體變數 | p.x = 1.0; |
-> | 結構體指標 | ptr->x = 1.0; |
struct point p = { 1.0, 2.0 };
struct point *ptr = &p;
printf("x = %f, y = %f\n", p.x, ptr->y); // 等價
struct point p = {1.0, 2.0};p = {1.0, 2.0}; ❌ 編譯錯誤struct point p1 = {1.0, 2.0};
struct point p2 = p1; // ✓
p2 = p1; // ✓
struct point *ptr = malloc(sizeof(struct point)); ptr->x = 3.0; ptr->y = 4.0; free(ptr);
typedef 簡化型別名稱typedef struct {
double x, y;
} Point; // 現在可直接用 Point
Point p1, p2;
Point *ptr = malloc(sizeof(Point));
struct rectangle {
struct point top_left;
struct point bottom_right;
};
struct point points[10]; // 結構體陣列
sizeof(struct) 含填充,通常大於成員大小總和#pragma pack(n) 改變對齊邊界(n=1,2,4,8,16)// 12 位元組
struct A { char c1; short s; char c2; int i; };
// 8 位元組(優化後)
struct B { char c1; char c2; short s; int i; };
. 與 -> 運算子結構體是 C 語言建構複雜資料模型的基石。熟練掌握其宣告、初始化、記憶體佈局與指標操作,能讓你設計出清晰、高效且可維護的系統級程式碼。