struct tag { members } vars;,tag 可省略,vars 可省略(僅聲明模板)。struct point p = {10, 20}; 或指定成員 .x = 10(C99)。.,指針用 ->(p->x ≡ (*p).x)。struct key { char *word; int count; } keytab[] = {{"auto",0},{"break",1}};sizeof object 或 sizeof(type) 返回字節數(size_t)。#define,不可用於 #if(預處理器不識別)。typedef int Length;
typedef char *String;
typedef struct { char *word; int count; } Key;
typedef struct tnode *Treeptr;
typedef int (*PFI)(char *, char *); // 函數指針類型
不創建新類型,僅為現有類型起別名,增強可讀性。
<stdarg.h>#include
int sum(int first, ...) {
va_list ap;
va_start(ap, first); // first 為最後一個固定參數
int s = 0, val = first;
while (val != -1) {
s += val;
val = va_arg(ap, int);
}
va_end(ap);
return s;
}
// sum(2,3,4,-1) → 9
步驟:聲明 va_list → va_start 初始化 → 循環 va_arg 取參 → va_end 清理。至少需一個固定參數。
<string.h>| 函數 | 功能 |
|---|---|
strcpy/strncpy | 複製字符串/前 n 字符 |
strcat/strncat | 拼接字符串/前 n 字符 |
strcmp/strncmp | 比較字符串/前 n 字符 |
strlen | 長度(不含 \0) |
strchr/strrchr | 查找字符首次/最後出現位置 |
<ctype.h>isalpha, isupper, islower, isdigit, isalnum, isspace → 非 0 為真。toupper, tolower → 返回轉換後字符。int(可表示 unsigned char 或 EOF)。<math.h>均接受/返回 double:sin, cos, tan, asin, acos, atan, atan2, exp, log, log10, pow, sqrt, fabs, ceil, floor, fmod。
<stdlib.h>rand() → [0, RAND_MAX] 偽隨機整數。srand(seed) 設置種子。#define frand() ((double)rand() / (RAND_MAX + 1.0))。| 函數 | 原型 | 特點 |
|---|---|---|
| malloc | void *malloc(size_t n) | 分配 n 字節,不初始化 |
| calloc | void *calloc(size_t n, size_t size) | 分配 n*size 字節,清零 |
| free | void free(void *p) | 釋放 p 指向塊,p 需來自 malloc/calloc |
正確釋放鏈表:
for (p = head; p != NULL; ) {
q = p->next;
free(p);
p = q;
}
錯誤寫法 for(p=head; p; p=p->next) free(p); 會訪問已釋放內存。