一、基础语法快速参考
1.1 基本结构模板
#include <stdio.h>
#include <stdlib.h>
// 宏定义
#define MAX_SIZE 100
#define MIN(a,b) ((a) < (b) ? (a) : (b))
// 全局变量声明
int global_var = 0;
// 函数声明
void example_function(int param);
int main(int argc, char *argv[]) {
// 变量声明
int local_var = 10;
// 基本输入输出
printf("Hello, World!\n");
scanf("%d", &local_var);
// 函数调用
example_function(local_var);
return EXIT_SUCCESS;
}
// 函数定义
void example_function(int param) {
printf("Parameter value: %d\n", param);
}
1.2 常用数据类型速查
| 类型 | 大小(32位系统) | 格式说明符 | 取值范围 |
|---|---|---|---|
| char | 1字节 | %c | -128 到 127 |
| short | 2字节 | %hd | -32,768 到 32,767 |
| int | 4字节 | %d | -2,147,483,648 到 2,147,483,647 |
| long | 4字节 | %ld | 同int |
| long long | 8字节 | %lld | -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 |
| float | 4字节 | %f | 约±3.4e±38 (7位有效数字) |
| double | 8字节 | %lf | 约±1.7e±308 (15位有效数字) |
| void* | 4/8字节 | %p | 内存地址 |
二、内存管理技巧
2.1 动态内存分配模式
// 安全分配模式
int* create_int_array(size_t size) {
int *arr = malloc(size * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return arr;
}
// 使用示例
int main() {
size_t count = 10;
int *numbers = create_int_array(count);
// 使用数组...
free(numbers); // 释放内存
numbers = NULL; // 避免悬空指针
return 0;
}
2.2 常见内存错误处理
-
检测内存泄漏 (Valgrind工具):
valgrind --leak-check=full ./your_program
防御性编程技巧:
// 检查指针有效性
void safe_print(const char *str) {
if (str == NULL) {
fprintf(stderr, "Null pointer encountered\n");
return;
}
printf("%s\n", str);
}
// 安全字符串复制
void safe_strcpy(char *dest, const char *src, size_t dest_size) {
if (dest == NULL || src == NULL || dest_size == 0) {
return;
}
strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0';
}
三、数据结构实现
3.1 动态数组实现
typedef struct {
int *data;
size_t size;
size_t capacity;
} DynamicArray;
DynamicArray* da_create(size_t init_capacity) {
DynamicArray *da = malloc(sizeof(DynamicArray));
da->data = malloc(init_capacity * sizeof(int));
da->size = 0;
da->capacity = init_capacity;
return da;
}
void da_push_back(DynamicArray *da, int value) {
if (da->size >= da->capacity) {
da->capacity *= 2;
da->data = realloc(da->data, da->capacity * sizeof(int));
}
da->data[da->size++] = value;
}
void da_free(DynamicArray *da) {
free(da->data);
free(da);
}
3.2 哈希表实现
#define TABLE_SIZE 1024
typedef struct HashNode {
char *key;
int value;
struct HashNode *next;
} HashNode;
typedef struct {
HashNode **nodes;
} HashMap;
unsigned int hash(const char *key) {
unsigned int hashval = 0;
for (; *key != '\0'; key++) {
hashval = *key + 31 * hashval;
}
return hashval % TABLE_SIZE;
}
HashMap* hm_create() {
HashMap *hm = malloc(sizeof(HashMap));
hm->nodes = calloc(TABLE_SIZE, sizeof(HashNode*));
return hm;
}
void hm_put(HashMap *hm, const char *key, int value) {
unsigned int index = hash(key);
HashNode *node = malloc(sizeof(HashNode));
node->key = strdup(key);
node->value = value;
node->next = hm->nodes[index];
hm->nodes[index] = node;
}
int hm_get(HashMap *hm, const char *key) {
unsigned int index = hash(key);
HashNode *node = hm->nodes[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return -1; // 未找到
}
四、文件IO操作模式
4.1 安全文件读写
// 读取整个文件到缓冲区
char* read_file(const char *filename) {
FILE *fp = fopen(filename, "rb");
if (fp == NULL) return NULL;
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer = malloc(length + 1);
if (buffer == NULL) {
fclose(fp);
return NULL;
}
fread(buffer, 1, length, fp);
buffer[length] = '\0';
fclose(fp);
return buffer;
}
// 写入二进制数据
int write_binary(const char *filename, const void *data, size_t size) {
FILE *fp = fopen(filename, "wb");
if (fp == NULL) return 0;
size_t written = fwrite(data, 1, size, fp);
fclose(fp);
return written == size;
}
4.2 文件逐行处理
void process_file(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
perror("Failed to open file");
return;
}
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, fp)) != -1) {
// 处理每一行
printf("Line length: %zu\n", read);
printf("%s", line);
}
free(line);
fclose(fp);
}
五、多线程编程
5.1 POSIX线程基础
#include <pthread.h>
typedef struct {
int start;
int end;
int result;
} ThreadData;
void* calculate_sum(void *arg) {
ThreadData *data = (ThreadData*)arg;
int sum = 0;
for (int i = data->start; i <= data->end; i++) {
sum += i;
}
data->result = sum;
return NULL;
}
int parallel_sum() {
pthread_t thread1, thread2;
ThreadData data1 = {1, 500000, 0};
ThreadData data2 = {500001, 1000000, 0};
pthread_create(&thread1, NULL, calculate_sum, &data1);
pthread_create(&thread2, NULL, calculate_sum, &data2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return data1.result + data2.result;
}
5.2 线程同步技术
// 使用互斥锁保护共享数据
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_counter = 0;
void* increment_counter(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
shared_counter++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
// 使用条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0;
void* producer(void *arg) {
// 生产数据...
pthread_mutex_lock(&mutex);
ready = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return NULL;
}
void* consumer(void *arg) {
pthread_mutex_lock(&mutex);
while (!ready) {
pthread_cond_wait(&cond, &mutex);
}
// 消费数据...
pthread_mutex_unlock(&mutex);
return NULL;
}
六、性能优化技巧
6.1 编译器优化选项
# GCC常用优化标志
gcc -O2 -march=native -pipe -flto -o program program.c
# 各优化级别说明:
# -O0: 无优化(调试用)
# -O1: 基本优化
# -O2: 推荐优化级别
# -O3: 激进优化(可能增加代码大小)
# -Os: 优化代码大小
6.2 内联函数与宏
// 内联函数(类型安全)
static inline int max(int a, int b) {
return a > b ? a : b;
}
// 宏(避免多次计算)
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
// 使用示例
int a = 5, b = 10;
int m = max(a, b); // 内联函数调用
int c = CLAMP(12, 0, 10); // 宏展开
6.3 缓存友好代码
// 差:缓存不友好
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
process(array[j][i]); // 列优先访问
}
}
// 好:缓存友好
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
process(array[i][j]); // 行优先访问
}
}
七、调试与测试
7.1 GDB调试技巧
# 编译时加入调试信息
gcc -g -o program program.c
# 常用GDB命令
gdb ./program
(gdb) break main # 在main函数设置断点
(gdb) run # 运行程序
(gdb) next # 单步执行
(gdb) step # 进入函数
(gdb) print variable # 打印变量值
(gdb) backtrace # 查看调用栈
(gdb) watch variable # 监视变量变化
(gdb) continue # 继续执行
7.2 单元测试框架
使用Unity测试框架示例:
#include "unity.h"
void setUp(void) {
// 测试前的初始化
}
void tearDown(void) {
// 测试后的清理
}
void test_addition(void) {
TEST_ASSERT_EQUAL_INT(5, add(2, 3));
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_addition);
return UNITY_END();
}
八、跨平台开发
8.1 条件编译技巧
// 检测操作系统
#if defined(_WIN32) || defined(_WIN64)
#define OS_WINDOWS 1
#elif defined(__linux__)
#define OS_LINUX 1
#elif defined(__APPLE__)
#define OS_MAC 1
#endif
// 平台特定代码
#ifdef OS_WINDOWS
#include <windows.h>
void platform_specific() {
Sleep(1000); // Windows下的sleep
}
#elif defined(OS_LINUX)
#include <unistd.h>
void platform_specific() {
sleep(1); // Linux下的sleep
}
#endif
8.2 可移植数据类型
#include <stdint.h>
// 固定宽度整数类型
int8_t a; // 8位有符号整数
uint16_t b; // 16位无符号整数
int32_t c; // 32位有符号整数
uint64_t d; // 64位无符号整数
// 平台无关的类型别名
typedef uint32_t pixel_t;
九、安全编程实践
9.1 安全字符串处理
// 使用安全函数替代不安全的函数
char dest[20];
// 不安全
strcpy(dest, src);
// 安全替代方案
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
// 或者使用更安全的版本
snprintf(dest, sizeof(dest), "%s", src);
9.2 整数溢出防护
#include <limits.h>
// 安全的加法
int safe_add(int a, int b) {
if ((b > 0 && a > INT_MAX - b) ||
(b < 0 && a < INT_MIN - b)) {
// 处理溢出
return 0;
}
return a + b;
}
// 安全的乘法
int safe_multiply(int a, int b) {
if (a > 0) {
if (b > 0 && a > INT_MAX / b) {
// 正溢出
return 0;
}
if (b < 0 && a > INT_MIN / b) {
// 负溢出
return 0;
}
} else {
if (b > 0 && a < INT_MIN / b) {
// 负溢出
return 0;
}
if (b < 0 && a < INT_MAX / b) {
// 正溢出
return 0;
}
}
return a * b;
}
十、现代C语言特性
10.1 C11标准新特性
// 泛型选择
#define cbrt(X) _Generic((X), \
long double: cbrtl, \
default: cbrt, \
float: cbrtf \
)(X)
// 静态断言
_Static_assert(sizeof(int) == 4, "int must be 4 bytes");
// 多线程支持
#include <threads.h>
int run(void *arg) {
printf("Thread running\n");
return 0;
}
thrd_t thread;
thrd_create(&thread, run, NULL);
thrd_join(thread, NULL);
10.2 有用的编译器扩展
// GCC的属性语法
void fatal_error() __attribute__((noreturn));
// 分支预测优化
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
if (unlikely(error_condition)) {
// 处理错误
}
// 内存对齐
struct aligned_data {
int x;
} __attribute__((aligned(64)));