zoukankan      html  css  js  c++  java
  • 四:C语言基础复习--指针(函数指针)

    函数指针:一个指针,指向的内存是函数。

    • 1、普通函数指针的定义与使用
    • 2、两个较为特殊的实例
    • 3、指向函数的指针数组
    • 4、指向函数的指针数组的行指针。

    一:普通函数指针的定义与使用

    #include<stdio.h>
    char* function(const char *t1,const char *t2)
    {
      //执行函数功能代码。。。
      //返回字符指针    
    }
    int main()
    {
      char * (*func)(char *t1,char *t2);
     func=&function;//或者func=function直接赋值
      func("hello","world");
      return 0;  
    }

    //也可以通过下面的代码定义一个函数指针类型
    ReturnType *(FunctionPointType*)(Parameter...)

    二:两个实例的分析

    #include<stdio.h>
    int function()
    {
      //函数功能实现代码。。。
      //返回值为int  
    }
    int main()
    {
      void (*p)();
      *(int*)&p=(int)function;
    (*p)(); return 0; }
    (*(void(*) ())0)();
    代码分析:将0转换成指向无参,无返回值的函数指针,取0地址内存的内容,然后调用函数。

    三:函数指针数组的使用

    #include<stdio.h>
    char* function1(char* temp)
    {
      printf("%s",temp);
    }
    char* function2(char* temp)
    {
      printf("%s",temp);
    }
    char* function3(char* temp)
    {
      printf("%s",temp);
    }
    int main()
    {
     char* (*p[3])(char* temp);
     p[0]=function1;
     p[1]=function2;
     p[2]=function3;
     p[0]("func1");
     p[1]("func2");
     p[2]("func3");
     return 0;
    }

    四:函数指针数组指针的使用

    #include<stdio.h>
    #include<string.h>
    char* function1(const char* temp)
    {
      printf("%s",temp);
       return (char*)0;
    }
    char* function2(const char* temp)
    {
      printf("%s",temp);
       return (char*)0;
    }
    char* function3(const char* temp)
    {
      printf("%s",temp);
      return (char*)0;
    }
    int main()
    {
     //定义一个函数指针数组。
     char* (*p[3])(const char*);
     //定义一个指向函数指针数组的行指针
     char* (*(*pa)[3])(const char*p);
     pa=&p;
     p[0][0]=&function1;
     p[0][1]=&function2;
     p[0][1]=&function3;
     pa[0][0]("func1");
     pa[0][1]("func2");
     pa[0][2]("func3");
     return 0;
    }

    程序分析:定义了一个函数指针数组,又定义了一个指向函数指针数组的行指针,通过行指针调用函数。

  • 相关阅读:
    linux安装pip
    keepalived 安装和配置
    SecureCRT突然卡死的问题
    python url合并与分离
    centos 长久路由表
    linux shell中 if else以及大于、小于、等于逻辑表达式介绍
    mtime,ctime,atime
    linux学习初体验
    Python数据库连接池DBUtils
    Flask 中的蓝图(BluePrint)
  • 原文地址:https://www.cnblogs.com/running-world/p/11573463.html
Copyright © 2011-2022 走看看