首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言入門

C 標準庫函數速查手冊:錯誤碼、數學、字元、字串、記憶體、通用工具

     編輯:C 語言入門

核心觀念:不用背,查手冊/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*)

使用建議

  1. 編譯器警告 -Wall -Wextra 全開
  2. 檢查回傳值(NULL、EOF、非 0)
  3. 緩衝區大小留餘裕,防溢位
  4. 二進制檔務必用 b 模式
  5. 隨機數嚴謹場景請用 /dev/urandom 或 C++11 <random>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved