菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
485
0

函数指针

原创
05/13 14:22
阅读数 11525

1.首先来讲讲函数

其实每个函数名,都是函数的入口地址,如下图所示:

 

其中0x4013B0就是上图的func()函数的入口地址,从上图可以看到,func&func的地址都一样,所以&对于函数而言,可以不需要

2.接下来便使用函数指针来指向上面func()函数

实例1如下:

#include "stdio.h"

int func(int x)
{
   return x;
}

int main()
{
  int (*FP)(int); //定义FP函数指针

  FP=func;        //FP指向func的地址

  printf("%d\n",FP(1));

  printf("%p,%p\n",FP,func);
 
  return 0;  
}

输出结果:

1                 //调用func()函数
004013B0,004013B0       

2)当使用typedef,函数指针使用如下:

#include "stdio.h"

int func(int x)
{
   return x;
}

typedef  int (*FP)(int);    //使用声明函数指针类型FP

int main()
{
  FP a;   //通过FP,定义函数指针a
  
  a=func;    //a指向func的地址

  printf("%d\n",a(1));  

  printf("%p,%p\n",a,func);

  return 0;  
} 

3)其实也可以先声明函数类型,再来定义函数指针:

 

#include "stdio.h"

int func(int x)
{
   return x;
}

typedef  int (FP)(int);    //使用声明函数类型FP

int main()
{
  FP* a;   //通过FP,定义函数指针a
  
  a=func;    //a指向func的地址

  printf("%d\n",a(1));  

  printf("%p,%p\n",a,func);

  return 0;  
} 

 

3.函数指针数组

示例:

#include <iostream>

using namespace std;

void func1(int i)
{
    cout<<"func1"<<endl;
}

void func2(int i)
{
    cout<<"func2"<<endl;
}
void func3(int i)
{
    cout<<"func3"<<endl;
}
void func4(int i)
{
    cout<<"func4"<<endl;
}


int main()
{
    void (*fp[3])(int);
    
    fp[0]=func1;
    fp[1]=func2;
    fp[2]=func3;
    
    fp[0](1); 
}

 

发表评论

0/200
485 点赞
0 评论
收藏