函数指针

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
",FP(1));

  printf("%p,%p
",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
",a(1));  

  printf("%p,%p
",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
",a(1));  

  printf("%p,%p
",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); 
}
原文地址:https://www.cnblogs.com/lifexy/p/8447268.html