内容范围
压缩包分为两部分:
c-basics/:基础语法c-advanced/:数组、指针、结构体、递归、链表等内容
1. 输入输出
printf
常见占位符:
%d:整型%c:字符型%f:浮点型%.2f/%.4f:控制小数位数
示例:
int i = 3;
char c = 'A';
float f = 11.45;
printf("i=%d\n", i);
printf("c=%c\n", c);
printf("f=%.4f\n", f);
scanf
示例:
scanf("%d %c", &x, &y);
要点:
- 输入变量时要传地址
%c前面的空格可以跳过空白字符
2. 分支结构
if / else
if (a > b){
printf("a 更大");
}
else{
printf("a不比b大\n");
}
if / else if / else
if (a > b){
printf("a 更大");
}
else if (a == b){
printf("a 和 b 一样大");
}
else{
printf("b 更大");
}
3. 运算符
算术运算符
+ - * / % ++ --
整数除法向 0 取整:
5 / 2 // 2
-5 / 2 // -2
浮点除法才会保留小数:
5 / 2.0 // 2.5
关系运算符
== != > < >= <=
逻辑运算符
&&:与||:或!:非
赋值运算符
=+= -= *= /=
位运算符
&按位与|按位或^按位异或~按位取反<<左移,常可以理解成乘 2 的幂>>右移,对正数常可以理解成除 2 的幂
4. 循环结构
while
while (x < 10){
printf("%d\n", x);
x++;
}
特点:先判断,后执行。
do...while
do {
printf("%d\n", x);
x++;
} while (x < 10);
特点:先执行一次,再判断。
也就是说,哪怕条件一开始不满足,也会先跑一轮。
for
for (i = 1; i < 10; i++){
printf("%d\n", i);
}
for 特别适合计数型循环,后面数组、排序、矩阵、图的邻接矩阵都会大量用它。
5. break 和 continue
break
作用:直接结束当前循环。
if (x == 5){
break;
}
continue
作用:跳过当前这一轮,进入下一轮循环。
if (x == 5){
x++;
continue;
}
6. 函数
示例:
int f(int x){
int y = 0;
y = x*x + 5*x + 1;
return y;
}
然后在 main 中反复调用:
a = f(5);
b = f(6);
c = f(7);
核心理解
函数就是把一个固定功能打包起来,后面需要时直接调用。 函数包括:
- 函数名
- 输入参数
- 返回值
如果没有返回值可以用 void。
7. 实参与形参
示例:
int f(int x)
x是形参
f(5)
5是实参
8. 数组
示例:
int arr[5];
int arr[5] = {1, 2, 3, 4, 5};
遍历:
for (int i = 0; i < 5; i++){
printf("%d", arr[i]);
}
arr除了代表整个数组名,也常表示数组首地址
这其实就是顺序表、指针运算、函数传数组的底层直觉来源。
备注:数组在内存中连续存放,arr 也可表示首地址。
9. 指针
示例:
int x = 10;
int* y = &x;
x:变量值&x:变量地址y:保存地址的指针变量*y:通过地址取值y:保存地址*y:根据地址取值
10. malloc
示例:
int* p;
p = (int*)malloc(4);
malloc可以在堆区申请一块内存- 返回的是这块内存的首地址
- 所以常常要用指针接住
如果你想申请一个 int 的空间,更推荐写:
int* p = (int*)malloc(sizeof(int));
这样比写死 4 更安全。
表示在内存中申请空间,并返回首地址。
11. 结构体 struct
示例:
struct student
{
int id;
int age;
float height;
};
使用:
struct student student1;
student1.id = 1008;
12. typedef
写法一
struct student
{
int id;
int age;
float height;
};
typedef struct student Stu;
写法二
typedef struct student
{
int id;
int age;
float height;
} Stu;
之后可以直接写:
Stu student1;
13. 递归
示例:
int factorial (int n){
if (n == 0){
return 1;
}
else{
return n * factorial (n - 1);
}
}
14. 引用与指针
07reference.c
int& ref = x;
这是 C++ 引用写法,不是标准 C 语法。
07reference-pointer.c
int x = 10;
int* ref = &x;
*ref = 20;
这是用指针间接修改变量。
15. 链表



结点定义:
struct LNode
{
int data;
struct LNode* next;
};
data:数据域next:指针域,指向下一个结点 创建结点:
head = (struct LNode*) malloc(sizeof(struct LNode));
middle = (struct LNode*) malloc(sizeof(struct LNode));
last = (struct LNode*) malloc(sizeof(struct LNode));
连接结点:
head -> next = middle;
middle -> next = last;
last -> next = NULL;
遍历时应写成:
p = head;
while (p != NULL)
{
printf("当前链表节点的数据为 %d\n", p -> data);
p = p -> next;
}