C 语言 stdlib.h
更新时间:2026-08-26。本文是
languages/c/主题入门层第 67 篇。stdlib.h是 C 的"万能工具库":字符串转数字、绝对值、快速排序、随机数、调外部命令……前面学 malloc/free 就出自这里。这一篇把最常用的函数串一遍,重点是字符串转数字的正确姿势——atoi用起来爽,但错误处理是裸奔。
本文要回答的问题
- 字符串怎么安全地转成数字?
- stdlib.h 里还有哪些高频函数?
atoi和strtol差在哪?
一、字符串 → 数字
c
#include <stdlib.h>
int i = atoi("123"); // 123
double d = atof("3.14"); // 3.14
long l = atol("100000"); // 100000atoi 的毛病:无法检测转换错误——"abc" 转出 0,"999999999999999"(溢出)转出随机值,你都分辨不出来。
strtol 是安全版,能报告错误:
c
char *endptr;
errno = 0;
long v = strtol("123abc", &endptr, 10);
if (errno == ERANGE) {
/* 溢出 */
} else if (endptr == "123abc") {
/* 一个字符都没转,输入非法 */
} else {
/* v 有效,endptr 指向第一个未转换字符 */
}| 函数 | 检查溢出 | 定位未转字符 | 适用 |
|---|---|---|---|
atoi | 不能 | 不能 | 已知合法的快速转换 |
strtol/strtod | 能 | 能 | 需要健壮性时 |
二、数字 → 字符串
C 没有标准的 itoa(它不是标准库函数)。标准做法用 sprintf/snprintf:
c
char buf[32];
snprintf(buf, sizeof(buf), "%d", 123); // "123"或用 snprintf 的返回值。注意别用非标准的 itoa——有的编译器没有,移植性差。
三、qsort:万能排序
配合函数指针与 qsort,任何类型都能排:
c
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y); // 避免溢出
}
int arr[] = {5, 2, 8, 1, 9};
qsort(arr, 5, sizeof(int), cmp_int); // 升序c
// 结构体按 score 排序
int cmp_score(const void *a, const void *b) {
const Student *sa = a, *sb = b;
return (sa->score > sb->score) - (sa->score < sb->score);
}
qsort(students, n, sizeof(Student), cmp_score);比较函数返回:负(a 在前)、0(相等)、正(b 在前)。
四、abs 与 system
c
int x = abs(-5); // 5(int 版,math.h 的 fabs 是浮点版)
system("ls -l"); // 执行外部命令(有安全隐患,谨慎用)system 会启动一个 shell 执行字符串——用户可控内容传给它有命令注入风险,生产代码尽量避免。
五、stdlib 全家桶一览
| 分类 | 函数 |
|---|---|
| 内存 | malloc、calloc、realloc、free |
| 字符串→数字 | atoi、atof、strtol、strtod |
| 数字→字符串 | snprintf(stdlib 外的 printf 族) |
| 排序/查找 | qsort、bsearch |
| 数值工具 | abs、labs、div |
| 其他 | rand/srand、system、exit、getenv |
六、常见坑对照
| 坑 | 现象 | 对策 |
|---|---|---|
| 用 atoi 转不可信输入 | 错误静默 | 用 strtol + errno |
| 用非标准 itoa | 编译不过 | snprintf |
| qsort 比较函数返回溢出 | 排序错乱 | (x>y)-(x<y) 写法 |
| 比较函数忘转型 | 指针错乱 | const void* 转具体类型 |
| system 传用户输入 | 命令注入 | 避免/校验 |
七、与本站主线衔接
- 排序的完整对比与实现,见排序算法实现;
- 随机数的使用,见rand 与 srand;
- 内存函数细节,见malloc 与 free。
一句话总结
stdlib.h 是 C 的工具箱:atoi 快但裸奔,健壮转换用 strtol + errno;snprintf 替代非标准的 itoa;qsort + 比较函数(返回 (x>y)-(x<y))实现万能排序——字符串转数字的错误处理,是新手最容易"裸奔"的地方。