函数指针和指针函数

指针函数:是一个函数,返回值是个指针,定义形式:int *fun(int x,int y)                                                                                类型标识符 *函数名(参数表)     int *f(x,y);                                                                                                                函数指针:是一个指针,指向的地址是一个函数 定义形式: int (*p)(int x,int y)                                                                     类型说明符 (*函数名)(参数

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int *f(int a,int b)
{
   int *p=(int *)malloc(sizeof(int));
   printf("the memory address of p=0x%x\n",p);
   memset(p,0,sizeof(int));
   *p=a+b;
   printf("*p=%d\n",*p);
   return p;
}
int main()
{
    printf("----------------start\n");
    int *p1=NULL;
    printf("the memory address of p1=0x%x\n",p1);
    p1=f(1,2);
    printf("the memory address of p1=0x%x\n",p1);
    printf("*p1=%d\n",*p1);
    getchar();
    return 0;
}

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int *f(int a,int b)
{
   int *p=(int *)malloc(sizeof(int));
   printf("the memory address of p=0x%x\n",p);
   memset(p,0,sizeof(int));
   *p=a+b;
   printf("*p=%d\n",*p);
   return p;
}
int main()
{
    printf("----------------start\n");
    int *p1=NULL;
    printf("the memory address of p1=0x%x\n",p1);
    p1=f(1,2);
    printf("the memory address of p1=0x%x\n",p1);
    printf("*p1=%d\n",*p1);
    getchar();
    return 0;
}

liuzj@ET302Buildver:~/zhanghong/king/123$ ./a.out 
----------------start
the memory address of p1=0x0
the memory address of p=0x234f010
*p=3
the memory address of p1=0x234f010
*p1=3

函数指针:

#include<stdio.h>
int max(int a,int b)
{
    return a>b?a:b;
}
int min(int a,int b)
{
    return a<b?a:b;
}
int (*f)(int,int);
int main()
{
    printf("------------------start\n");
    f=max;
    int c=0;
    c=(*f)(1,2); //函数指针的用法,通过指针来调用函数!

    printf("The max value is %d\n",c);
    f=min;
    c=(*f)(1,2);
    printf("the min value is %d\n",c);
    printf("----------------------End\n");
    getchar();
    return 0;
}

liuzj@ET302Buildver:~/zhanghong/king/123$ ./a.out 
------------------start
The max value is 2
the min value is 1
----------------------End

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值