Chinaunix首页 | 论坛 | 博客
  • 博客访问: 64175
  • 博文数量: 16
  • 博客积分: 45
  • 博客等级: 民兵
  • 技术积分: 171
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-09 15:38
文章分类

全部博文(16)

文章存档

2014年(3)

2013年(7)

2012年(6)

我的朋友

分类: 嵌入式

2013-04-09 14:51:54

函数也有地址

  1. #include <stdio.h>
  2. void func(void);

  3. int main(void)
  4. {
  5.    int i = 3;
  6.    printf("i resides at %p\n", &i);
  7.    printf("func() resides at %p\n", &func);
  8.    printf("main() resides at %p\n", &main);
  9.    return 0;
  10. }


  11. void func(void)
  12. {
  13.    printf("hello world\n");
  14. }

函数指针:
以下为转载:

  1. #include <stdlib.h>
  2. #include <stdio.h>

  3. void fun(int); /* 函数声明 */
  4. int main(void)
  5. {
  6.     int x = 6;
  7.     void (*p)(int); /* 定义函数指针变量 */
  8.     p = &fun; /* 将fun函数的首地址赋给函数指针变量p*/
  9.     fun(x); /* 直接调用fun函数 */
  10.     (*p)(x); /* 通过函数指针变量p调用fun函数 */
  11.     return 0;
  12. }

  13. void fun(int x) /* 函数定义 */
  14. {
  15.   printf("%d\n", x);
  16. }

函数指针的应用:

点击(此处)折叠或打开

  1. #include "stdio.h"
  2. #include "string.h"

  3. #define CMD_COUNT (sizeof (cmd) / sizeof (cmd[0]))

  4. /* Command definitions structure. */
  5. typedef struct scmd
  6. {
  7.    char val[8];
  8.    void (*func)(char *par);//函数指针,它指向 "void function_name(char *par)"这种形式的函数
  9. } SRAM;
  10.     
  11. static void cmd_capture (char *par)
  12. {
  13.     printf(par);
  14. }

  15. static void cmd_type (char *par)
  16. {
  17.     printf(par);
  18. }
  19. static void cmd_rename (char *par)
  20. {
  21.     printf(par);
  22. }

  23. static void cmd_copy (char *par)
  24. {
  25.     printf(par);
  26. }

  27. static void cmd_delete(char *par)
  28. {
  29.     printf(par);
  30. }

  31. static void cmd_dir (char *par)
  32. {
  33.     printf(par);
  34. }

  35. static void cmd_format (char *par)
  36. {
  37.     printf(par);
  38. }

  39. static const SRAM cmd[] = {
  40.    "CAP", cmd_capture,
  41.    "TYPE", cmd_type,
  42.    "REN", cmd_rename,
  43.    "COPY", cmd_copy,
  44.    "DEL", cmd_delete,
  45.    "DIR", cmd_dir,
  46.    "FORMAT", cmd_format};

  47. int main(void)
  48. {
  49.     char * str = "CAP";
  50.     if(strcmp (str, cmd[0].val) == 0 )
  51.     {
  52.         printf("ok\n");
  53.     }
  54.     else
  55.     {
  56.         printf("no\n");
  57.     }
  58.     cmd[0].func("china!!!\n");
  59. }



阅读(984) | 评论(0) | 转发(0) |
0

上一篇:一级指针和二级指针

下一篇:Arduino DMX

给主人留下些什么吧!~~