关于C的声明解读
C语言是英语为母语的人发明的,阅读习惯也是英语阅读的习惯,中文有时候读和看有点别扭。
1、变量声明比如(可以从右往左读):
//英文:p is a pointer to int
//中文:p是指向int的指针
int *p
再比如:
//英文:p is a pointer to const char
//中文:p是指向const char的指针
//解释:p地址可以改变,p指向的内容不可改变
const char *p;
//英文: p is a const pointer to char
//中文:p 是一个指向char的const pointer
//解释: p 地址不可改变,但是指向的内容可以改变,所以定义的时候需要给它赋值。
char * const p;
2、数组
//英文:StudentName is array of pointer to char
//中文:StudentName 是一个指向char的指针的数组
//解释1:StudentName是一个数组,什么数组呢?char 指针的数组
//解释2:因为StudentName 是指针的数组,所以StudentName是StudentName[0]地址的指针,也就是*StudentName和StudentName[0]等价
char *StudentName[] = {
"James",
"Curry",
"Durant"
}
3、函数
//英文:func is a function(int num) return a pointer to int
//中文:func是一个返回int指针的函数,函数参数是int
//解释:func返回的是一个int指针
//使用:int *tmp = func(num);
int *func(int num);
//英文:func is a pointer of function(int num) return int
//中文:func 是一个function(int num)的函数指针,这个函数返回int
//解释:func 是一个指针,指向一个函数function(int num)
int (*func)(int num);
//使用1,回调函数
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int test(int (*func)(int t),int num){
5 printf("test\n");
6 return func(num);
7 }
8 int f1(int t){
9 return t + 10;
10 }
11 int main(){
12 int res = test(f1,3);
13 printf("res:%d\n",res);
14 }
//使用2,类似于面向对象的方法
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int f1(int num){
5 return num + 10;
6 }
7
8 struct student {
9 char *name;
10 int (*f1)(int num);
11 };
12
13 int main(){
14 struct student S;
15 S.f1 = f1;
16 int res = S.f1(3);
17 printf("res:%d\n",res);
18 }
//解释:func是一个数组,什么数组呢?指针的数组,指针指向谁呢?指向函数
int (*func[])();
//使用3,函数数组
1 #include <stdio.h>
2 #include <stdlib.h>
3 int f1(int t){
4 return t + 10;
5 }
6
7 int f2(int t){
8 return t + 11;
9 }
10 int (*func[])() = {
11 f1,
12 f2
13 };
14
15 int main(){
16 int res = func[1](3);
17 printf("res:%d\n",res);
18 }