zoukankan      html  css  js  c++  java
  • 函数指针

    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); 
    }
  • 相关阅读:
    工作笔记之20170223:①关于Html5的placeholder属性,②以及input的outline:none的样式问题
    工作笔记之:如何在eclipse安装CVS插件?找了很久的,自己总结一下
    ajax后台请求两种方法(js和jQuery)
    22
    21
    20
    19
    18
    17
    16
  • 原文地址:https://www.cnblogs.com/lifexy/p/8447268.html
Copyright © 2011-2022 走看看