一、基础结构
- 程序框架
c
#include <stdio.h> // 头文件包含
int main() { // 主函数入口
printf("Hello World!\n");
return 0; // 返回值
}
- 注释
c
// 单行注释
/* 多行注释
第二行 */
二、数据类型与变量
-
基本数据类型
-
变量声明与初始化
c
int x = 5; // 声明并初始化
float y; // 仅声明
y = 2.718; // 后续赋值
- 常量
c
const int MAX = 100; // const常量
#define PI 3.14159 // 宏定义常量
三、运算符
- 算术运算符
c
int a = 10, b = 3;
int sum = a + b; // 13
int mod = a % b; // 1(取余)
- 位运算符
c
unsigned char c = 0b1010; // 二进制表示
c = c << 1; // 左移1位:0b10100(十进制20)
c = c & 0x0F; // 按位与:保留低4位
- 逻辑运算符
c
if (a > 5 && b < 10) { // 逻辑与
// 条件成立时执行
}
四、控制结构
- 条件语句
c
// if-else
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("C\n");
} else {
printf("Fail\n");
}
// switch-case
switch (grade) {
case 'A': printf("Excellent\n"); break;
case 'B': printf("Good\n"); break;
default: printf("Invalid\n");
}
- 循环语句
c
// for循环
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
// while循环
int j = 0;
while (j < 5) {
printf("%d ", j++);
}
// do-while循环
int k = 0;
do {
printf("%d ", k++);
} while (k < 3);
五、函数
- 函数定义与调用
c
// 函数声明
int add(int a, int b);
// 函数定义
int add(int a, int b) {
return a + b;
}
// 调用
int result = add(3, 4); // result = 7
- 递归函数
c
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
六、数组与字符串
- 数组
c
int arr[5] = {1, 2, 3, 4, 5}; // 初始化
arr[2] = 10; // 修改第三个元素
// 多维数组
int matrix[2][3] = {{1,2,3}, {4,5,6}};
2. 字符串
c
char str1[] = "Hello"; // 自动补'\0'
char str2[10];
strcpy(str2, str1); // 复制字符串
printf("Length: %d\n", strlen(str1)); // 输出5
七、指针
- 指针基础
c
int num = 42;
int *p = # // p指向num的地址
printf("%d", *p); // 输出42(解引用)
// 指针运算
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d", *(ptr + 1)); // 输出20
- 指针与函数
c
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int x = 1, y = 2;
swap(&x, &y); // x=2, y=1
八、结构体与联合体
- 结构体
c
struct Student {
char name[20];
int age;
float score;
};
// 使用
struct Student s1;
strcpy(s1.name, "Alice");
s1.age = 18;
- 联合体
c
union Data {
int i;
float f;
char str[4];
};
union Data data;
data.i = 0x12345678; // 共享同一内存空间
九、文件操作
- 读写文件
c
FILE *fp = fopen("test.txt", "w");
if (fp != NULL) {
fprintf(fp, "Write to file\n");
fclose(fp);
}
// 读取文件
char buffer[100];
fp = fopen("test.txt", "r");
fgets(buffer, 100, fp);
printf("%s", buffer);
十、预处理器指令
- 宏定义
c
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int max_val = MAX(3, 5); // 5
// 条件编译
#ifdef DEBUG
printf("Debug mode\n");
#endif
- 头文件包含
c
#include "myheader.h" // 自定义头文件
十一、动态内存管理
c
int *arr = (int*)malloc(5 * sizeof(int)); // 动态分配
if (arr != NULL) {
arr[0] = 10;
free(arr); // 释放内存
}
// 避免野指针
arr = NULL;
总结
核心重点:
指针操作(内存地址访问)和内存管理(malloc/free)是C语言的核心难点。
结构体用于组织复杂数据,联合体节省内存空间。
常见错误:
数组越界、内存泄漏、野指针。
未初始化的变量导致未定义行为。
练习建议:
实现链表、栈等数据结构。
结合单片机外设(如GPIO、UART)编写硬件驱动代码。
示例代码(链表节点定义):
c
struct Node {
int data;
struct Node *next;
};
掌握这些语法后,可进一步学习算法优化和嵌入式系统开发中的实际应用。