函数指针的2个例子

第一个是我写的程序:

//函数指针的用法

//---------------------Include Files-------------

#include <stdio.h>

#include <math.h>

//-----------------end Include Files-------------

double BISECTION(double x0, double (*funcptr)(double));

double func(double x)

{

return ( x * x );

}

int main()

{

printf("%lf/n", BISECTION(2.0, func));//func前加取地址号&也可以

return 0;

}

double BISECTION(double x0, double (*funcptr)(double))

{

return  (*funcptr)(x0);//return funcpstr(x0)也能执行

// return funcpstr(x0);//不加*号和括号出现外部链接的错误,但不应该出现错误啊??

//在VS2005中,不加*号和括号可以顺利执行

}

 

另一个是改写自参考书上的程序

//函数指针的用法

//---------------------Include Files-------------

#include

#include

//-----------------end Include Files-------------

typedef double (*funcptr) (double);

double func(double x)

{

return ( x * x );

}

int main()

{

double y = 2.0;

int x;

funcptr fp;

funcptr function[6] = {func, sin, cos, tan, log, exp};

printf("Enter x, which lies between 0 to 5: ");

scanf("%d", &x);

fp = function[x];

// fp = &func;

// fp = func;//这两种写法都可以调用func函数

printf("%lf/n", fp(2));

printf("%lf/n", (*fp)(2));

return 0;

}

//本程序改写自《C语言程序设计实用教程(Applied C: An Introduction and More)》,[美]

//Alice E. Fischer, David W. Eggert等著,裘岚、张晓芸等译,电子工业出版社,

//2001年9月第1版, 第622页程序

//"由于fp是一个指针,*fp表示fp所指向的函数,(*fp)(x)以实参x调用该函数,因此(*fp)(x)是

//合法并有意义的语句。C语法允许仅使用函数指针,而无需写星号和括号",摘自上书

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值