跳转到内容

C 语言库函数

来自代码酷

模板:Note

C语言库函数概述[编辑 | 编辑源代码]

C语言库函数(Library Functions)是由C标准库(如glibc、MSVCRT等)及第三方库提供的预编译函数集合,涵盖输入输出、字符串处理、数学运算等常见操作。这些函数遵循ISO C标准规范,通过头文件(.h)声明,极大提升了代码复用性和开发效率。

核心特点[编辑 | 编辑源代码]

  • 标准化:ANSI C定义了标准库函数(如<stdio.h>, <math.h>)
  • 跨平台性:在不同操作系统/编译器下行为一致
  • 性能优化:底层通常由汇编语言实现
  • 模块化:按功能分类到不同头文件

主要库函数分类[编辑 | 编辑源代码]

下表列出C标准库的核心头文件及典型函数:

头文件 功能描述 示例函数
<stdio.h> 标准输入输出 printf(), scanf(), fopen()
<stdlib.h> 内存管理/类型转换 malloc(), atoi(), rand()
<string.h> 字符串操作 strcpy(), strlen(), strcmp()
<math.h> 数学运算 sqrt(), sin(), pow()
<time.h> 时间处理 time(), clock(), strftime()

详细函数解析[编辑 | 编辑源代码]

输入输出函数(stdio.h)[编辑 | 编辑源代码]

printf() 格式化输出[编辑 | 编辑源代码]

#include <stdio.h>
int main() {
    int age = 25;
    printf("Name: %s\nAge: %d\nScore: %.2f\n", 
           "Alice", age, 95.5f);
    return 0;
}

输出:

Name: Alice
Age: 25
Score: 95.50

格式说明符:

  • %d - 十进制整数
  • %f - 浮点数(%.2f保留两位小数)
  • %s - 字符串

字符串函数(string.h)[编辑 | 编辑源代码]

内存安全操作示例[编辑 | 编辑源代码]

#include <stdio.h>
#include <string.h>

int main() {
    char src[20] = "Hello";
    char dest[20];
    
    // 安全拷贝(避免缓冲区溢出)
    strncpy(dest, src, sizeof(dest)-1);
    dest[sizeof(dest)-1] = '\0';
    
    printf("Length: %zu\n", strlen(dest));
    return 0;
}

数学函数(math.h)[编辑 | 编辑源代码]

三角函数计算[编辑 | 编辑源代码]

graph LR A[输入角度值] --> B[转换为弧度] B --> C[调用sin/cos/tan] C --> D[输出结果]

#include <math.h>
#include <stdio.h>

#define PI 3.14159265

int main() {
    double angle = 45.0;
    double radians = angle * (PI / 180.0);
    printf("sin(%.2f°) = %.4f\n", angle, sin(radians));
    return 0;
}

高级应用技巧[编辑 | 编辑源代码]

函数指针与库函数[编辑 | 编辑源代码]

通过函数指针动态调用库函数:

#include <stdio.h>
#include <string.h>

typedef int (*compare_func)(const char*, const char*);

void sort_strings(char **arr, int n, compare_func cmp) {
    // 使用指定的比较函数排序
}

int main() {
    char *names[] = {"Bob", "Alice", "Charlie"};
    sort_strings(names, 3, strcmp);
    return 0;
}

错误处理机制[编辑 | 编辑源代码]

标准库通过以下方式报告错误:

  • 返回值(如fopen()返回NULL)
  • errno全局变量(需包含<errno.h>
  • perror()函数输出错误描述

性能考量[编辑 | 编辑源代码]

页面模块:Message box/ambox.css没有内容。

时间复杂度对比:

  • memcpy():O(n)
  • qsort():O(n log n)
  • bsearch():O(log n)

扩展阅读[编辑 | 编辑源代码]

模板:Exercise