本文深入解析 C 語言的複合型別系統:enum 列舉、struct 結構、typedef 類型別名、union 聯合,並附上完整程式碼範例與記憶體佈局分析。
enum COLOR { RED, YELLOW, GREEN };
列舉常數預設從 0 遞增,屬 int 型別。可指定值:enum { RED=1, YELLOW, GREEN=5 }。
NumCOLORS)、支援陣列索引。enum COLOR { RED, YELLOW, GREEN, NumCOLORS };
char *ColorNames[NumCOLORS] = { "red", "yellow", "green" };
// 使用 ColorNames[color] 直接查找,避免 switch
struct date { int month; int day; int year; };
struct date today = {6, 28, 2015}; // 依序賦值
struct date thismonth = {.month=6, .year=2015}; // 指定成員(C99)
today.day、pDate->month(指標用 ->)。p1 = p2(逐成員複製),陣列不支援此操作。struct date *p = &today;,注意結構變數名不是地址。const 防誤改。struct rectangle { struct point pt1; struct point pt2; };
struct rectangle r;
r.pt1.x = 10; // 多層存取
struct rectangle rects[] = { {{1,2},{3,4}}, {{5,6},{7,8}} };
struct time { int hour, min, sec; };
struct time ab = {1,5,7};
sizeof(ab) == 12; // 4+4+4,無填充
// 但結構內可能因對齊產生空洞,相鄰成員位址差不一定等於 sizeof(成員)
typedef int Length;
typedef struct { int month, day, year; } Date;
Date d = {9, 1, 2005}; // 直接用 Date,無需 struct 關鍵字
typedef long int64_t; 提升可移植性。typedef struct node { int data; struct node *next; } Node;typedef union { int i; char ch[sizeof(int)]; } CHI;
CHI chi; chi.i = 1234; // 0x000004D2
// 小端序輸出:D2 04 00 00