核心觀念:不用背,查手冊/man page,常用自然記
標準頭檔一覽
<ctype.h> <errno.h> <float.h> <limits.h> <locale.h>
<math.h> <setjmp.h> <signal.h> <stdarg.h> <stddef.h>
<stdlib.h> <stdio.h> <string.h> <time.h>
1. 錯誤處理 <errno.h>
errno:執行緒區域變數,初始 0,庫函數出錯設非 0
EDOM:定義域錯誤(如 sqrt(-1))
ERANGE:值域錯誤(溢位/欠位)
2. 數學函數 <math.h>(參數/回傳皆 double)
| 分類 | 函數 |
| 三角 | sin, cos, tan, asin, acos, atan, atan2(y,x) |
| 雙曲 | sinh, cosh, tanh |
| 指數/對數 | exp, log, log10 |
| 冪/根 | pow(x,y), sqrt |
| 絕對值 | fabs |
| 取整 | ceil(上), floor(下) |
| 分解 | frexp(x, *exp), ldexp(x,n), modf(x, *ip) |
| 餘數 | fmod(x,y) |
3. 字元判斷/轉換 <ctype.h>(回傳 int,非 0 為真)
isalpha, isdigit, isalnum, isspace, isupper, islower
iscntrl, isprint, isgraph, isxdigit, ispunct
toupper(c), tolower(c) // 非字母原樣回傳
4. 字串操作 <string.h>
| 功能 | 函數 |
| 長度 | strlen |
| 複製 | strcpy, strncpy |
| 連接 | strcat, strncat |
| 比較 | strcmp, strncmp |
| 搜尋字元 | strchr(首), strrchr(尾) |
| 搜尋子串 | strstr |
| 掃描集合 | strspn, strcspn, strpbrk |
| 分詞 | strtok |
| 錯誤訊息 | strerror(errno) |
5. 記憶體操作 <string.h>(void*,高效、可重疊)
memcpy(dest, src, n) // 複製 n byte,不可重疊
memmove(dest, src, n) // 可重疊安全
memcmp(s1, s2, n) // 比較 n byte
memchr(s, c, n) // 搜尋字元
memset(s, c, n) // 設定 n byte 為 c(常用 0 或 -1)
技巧:memset(arr, 0, sizeof(arr)) 清零陣列;memset(arr, -1, sizeof(arr)) 將所有位元置 1(有號整數變 -1)。
6. 通用工具 <stdlib.h>
隨機數
rand() // 0 ~ RAND_MAX
srand(seed) // 設定種子
動態記憶體
malloc(size) // 未初始化
calloc(n, size) // 歸零
realloc(ptr, new_size) // 調整大小,保留內容
free(ptr) // 釋放
整數運算
abs(n), labs(n)
div_t div(n,m) // 商 quot、餘 rem
ldiv_t ldiv(n,m)
字串轉數值
atof(s), atoi(s), atol(s)
程式控制
abort() // 異常終止
exit(status) // 正常終止
atexit(func) // 登記退出處理
system(cmd) // 執行殼層命令
getenv(name) // 讀取環境變數
搜尋/排序
bsearch(key, base, n, size, cmp) // 二分搜尋,需已排序
qsort(base, n, size, cmp) // 快速排序
// cmp 簽名:int cmp(const void*, const void*)
使用建議
- 編譯器警告
-Wall -Wextra 全開
- 檢查回傳值(NULL、EOF、非 0)
- 緩衝區大小留餘裕,防溢位
- 二進制檔務必用
b 模式
- 隨機數嚴謹場景請用
/dev/urandom 或 C++11 <random>