C语言速查
指针
int x = 42;
int *p = &x; /* 指向 x 的指针 */
*p = 100; /* 解引用 — x 变为 100 */
/* 指针算术 */
int arr[5] = {1,2,3,4,5};
int *q = arr;
printf("%d\n", *(q+2)); /* 3 */
/* 指针的指针 */
int **pp = &p;
printf("%d\n", **pp); /* 100 */
内存管理
#include <stdlib.h>
/* malloc — 未初始化 */
int *arr = malloc(10 * sizeof(int));
if (!arr) { /* 必须检查! */ exit(1); }
/* calloc — 零初始化 */
int *arr2 = calloc(10, sizeof(int));
/* realloc */
arr = realloc(arr, 20 * sizeof(int));
/* 必须释放避免内存泄漏 */
free(arr);
arr = NULL; /* 防止悬空指针 */
结构体
typedef struct {
char name[64];
int age;
float score;
} Student;
Student s = {"Alice", 20, 95.5f};
printf("%s: %d, %.1f\n", s.name, s.age, s.score);
/* 指向结构体的指针 */
Student *ps = &s;
printf("%s\n", ps->name); /* 箭头操作符 */
标准库
| 头文件 | 常用函数 |
|---|---|
| stdio.h | printf, scanf, fopen, fclose, fread, fwrite |
| stdlib.h | malloc, free, exit, atoi, qsort, bsearch |
| string.h | strlen, strcpy, strcat, strcmp, memcpy, memset |
| math.h | sqrt, pow, abs, floor, ceil, sin, cos |
| time.h | time, clock, difftime, strftime |