- #include <stdlib.h>
- #include <stdio.h>
- void fun(int); /* 函数声明 */
- int main()
- {
- int x = 6;
- void (*p)(int); /* 定义函数指针变量 */
- p = &fun; /* 将fun函数的首地址赋给函数指针变量p*/
- fun(x); /* 直接调用fun函数 */
- (*p)(x); /* 通过函数指针变量p调用fun函数 */
- return 0;
- }
- void fun(int x) /* 函数定义 */
- {
- printf("%d\n", x);
- }
- #include <stdlib.h>
- #include <stdio.h>
- typedef void (*FunType)(int, int); /* 定义函数指针类型FunType */
- void add(int, int); /* 函数声明 */
- void sub(int, int);
- void fun(FunType, int, int);
- int main()
- {
- int a = 2;
- int b = 3;
- fun(add, a, b); /* 将函数指针作为参数调用fun函数 */
- fun(sub, a, b);
- return 0;
- }
- void add(int a, int b) /* 两数相加 */
- {
- int result;
- result = a + b;
- printf("%d + %d = %d\n", a, b, result);
- }
- void sub(int a, int b) /* 两数相减 */
- {
- int result;
- result = a - b;
- printf("%d - %d = %d\n", a, b, result);
- }
- void fun(FunType p, int a, int b) /* 函数的参数为函数指针 */
- {
- (*p)(a, b);
- }