结构体和函数指针

  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
  1. 将struct student 结构体重命名为student;
    将struct student 结构体指针重命名为pstudent;
  2. 注意结构体中定义的 struct student *classmate,必须是指针,不然分配空间就变成了‘俄罗斯套娃’。指针在32位处理器中占4个字节。
  3. 程序中尽量避免使用全局变量,用函数返回值获取变量的值。
  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

三.函数指针

  1. 定义:int (*p)(int, int);

函数返回值类型 ( 指针变量名) (函数参数列表);*

“函数返回值类型”表示该指针变量可以指向具有什么返回值类型的函数;
“函数参数列表”表示该指针变量可以指向具有什么参数列表的函数。这个参数列表中只需要写函数的参数类型即可。

指向函数的指针变量没有 ++ 和 – 运算。

typedef int (*add_type) (int, int);
add_type f1; //定义函数指针
add_type f2; //定义函数指针

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值