一
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 typedef struct student {
6 char *name;
7 int age;
8 struct student *classmate;
9 void (*specialty)(void);//函数指针,占4个字节,本质是指针。
10 }student, * pstudent;
11
12
13 static void play_ball(){
14 printf("playball\n");
15 }
16 static void sing_song(){
17 printf("singsong\n");
18 }
19 int main()
20 {
21 int i;
22 printf("sizeof(play_ball)=%ld\n",sizeof(play_ball));
23 student ss[2] = {{"zhangsan", 40, NULL, play_ball}, {"lili", 30, NULL, sing_song}};
24 for (i = 0; i < 2; i++) {
25 ss[i].specialty();//注意用法
26 }
27
28 }
执行结果:
[annshen@try]$ ./a.out
sizeof(play_ball)=1
playball
singsong
- 将struct student 结构体重命名为student;
将struct student 结构体指针重命名为pstudent; - 注意结构体中定义的 struct student *classmate,必须是指针,不然分配空间就变成了‘俄罗斯套娃’。指针在32位处理器中占4个字节。
- 程序中尽量避免使用全局变量,用函数返回值获取变量的值。
- 注意函数指针的用法。
二:实际应用
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 typedef struct lcd {
6 int type;
7 void (*display_logo)(void);//函数指针,占4个字节,本质是指针。
8 }lcd, * p_lcd;
9
10
11 static void display_logo_a(){
12 printf("display_logo_a\n");
13 }
14 static void display_logo_b(){
15 printf("display_logo_b\n");
16 }
17
18 lcd lcds[2] = {{0, display_logo_a}, {1, display_logo_b}};
19
20 static int read_flash(){
21 return 1;
22 }
23 static p_lcd get_lcd_type() {
24 int type = read_flash();
25 return &lcds[type];
26 }
27 int main()
28 {
29 p_lcd plcd;
30 plcd = get_lcd_type();
31 plcd->display_logo();
32 return 0;
33 }
执行结果:
[annshen@ try]$ ./a.out
display_logo_b
三.函数指针
- 定义:int (*p)(int, int);
函数返回值类型 ( 指针变量名) (函数参数列表);*
“函数返回值类型”表示该指针变量可以指向具有什么返回值类型的函数;
“函数参数列表”表示该指针变量可以指向具有什么参数列表的函数。这个参数列表中只需要写函数的参数类型即可。
指向函数的指针变量没有 ++ 和 – 运算。
typedef int (*add_type) (int, int);
add_type f1; //定义函数指针
add_type f2; //定义函数指针