先復習函數的定義與函數的聲明:
//這是一個求和函數的定義:
int add(int x, int y)
{
return(x + y);
}
//可以這樣聲明:
int add(int x, int y);
//也可以這樣聲明:
int add(int, int);
定義一個函數指針聲明一個函數差不多, 用 (* ) 包括函數即可:
//像這樣:
int (*pfun)(int, int);
//或這樣:
int (*pfun)(int x, int y);
//也可以:
typedef int (*pfun)(int, int);
//這就聲明了一個叫 pfun 的函數指針, 能被它指向的函數一定要有相同的參數格式.
1. 簡單例子:
#include <stdio.h>
int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}
int main(void)
{
int (*pf)(int, int);
pf = add;
printf("%d\n", pf(9, 3)); /* 12 */
pf = sub;
printf("%d\n", pf(9, 3)); /* 6 */
pf = mul;
printf("%d\n", pf(9, 3)); /* 27 */
pf = div;
printf("%d\n", pf(9, 3)); /* 3 */
getchar();
return 0;
}
2. 函數指針數組:
#include <stdio.h>
int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}
int main(void)
{
int (*pf[4])(int, int) = {add, sub, mul, div};
printf("%d\n", pf[0](9, 3)); /* 12 */
printf("%d\n", pf[1](9, 3)); /* 6 */
printf("%d\n", pf[2](9, 3)); /* 27 */
printf("%d\n", pf[3](9, 3)); /* 3 */
getchar();
return 0;
}
3. 用函數指針做參數:
#include <stdio.h>
int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}
int math(int(*pfun)(int, int), int x, int y) {
return pfun(x, y);
}
int main(void)
{
printf("%d\n", math(add, 9, 3)); /* 12 */
printf("%d\n", math(sub, 9, 3)); /* 6 */
printf("%d\n", math(mul, 9, 3)); /* 27 */
printf("%d\n", math(div, 9, 3)); /* 3 */
getchar();
return 0;
}
返回“學點C語言 - 目錄”