C 語言提供三種用戶自定義類型機制:typedef 類型別名、struct 結構體、union 共用體。本文系統講解其語法、語義、內存佈局及最佳實踐。
typedef 現有類型 新類型名;
typedef int INTEGER;
typedef char* CHAR_PTR;
typedef struct { int x, y; } Point;
typedef 不創建新類型,僅是別名。INTEGER 與 int 完全等價。
struct Tag {
type1 member1;
type2 member2;
...
};
struct Date { int year, month, day; };
struct Student {
char name[20];
struct Date birthday; // 嵌套
float scores[4];
};
int 通常 4 字節對齊)。#pragma pack(n) 或屬性 __attribute__((packed)) 控制對齊。struct Student s1; // 棧上
struct Student *s2 = malloc(sizeof(struct Student)); // 堆上
union {
int i;
char c[4];
} u;
u.i = 0x01020304;
if (u.c[0] == 0x04) printf("Little-endian\n");
enum Type { INT, FLOAT, STRING };
struct Value {
enum Type tag;
union {
int i;
float f;
char *s;
} data;
};
頭文件僅聲明 struct Impl;,實現細節隱藏在 .c 文件中,實現封裝。
typedef struct { ... } Name; 定義自包含類型。