• C语言结构体中的函数指针


    这篇文章简单的叙述一下函数指针在结构体中的应用,为后面的一系列文章打下基础

    本文地址:http://www.cnblogs.com/archimedes/p/function-pointer-in-c-struct.html,转载请注明源地址。

    引言

    指针是C语言的重要组成部分, 于是深入理解指针并且高效地使用指针可以使程序员写出更加老练的程序。我们要记住指针是一个指向内存地址的变量。指针可以引用如int、char……常见的数据类型,例如:

    int * intptr;     // 声明一个指向整型值的指针 
    int intval = 5 ;  // 定义一个整型变量 
    intptr = & intval ; // intptr现在包含intval的地址

    指针不仅仅指向常规的类型还可以指向函数

    函数指针

    函数指针的内容不难理解,不再赘述,参见《C语言函数指针的用法

    语法

    要声明一个函数指针,使用下面的语法:

    Return Type  * function pointer's variable name ) ( parameters 

    例如声明一个名为func的函数指针,接收两个整型参数并且返回一个整型值

    int (*func)(int a , int b ) ; 

    可以方便的使用类型定义运用于函数指针:

    typedef int (*func)(int a , int b ) ; 

    结构体中的函数指针

    我们首先定义一个名为Operation的函数指针:

    typedef int (*Operation)(int a , int b );

    再定义一个简单的名为STR的结构体

    typedef  struct _str {
           int  result ; // 用来存储结果
           Operation  opt; // 函数指针 
    
     } STR;

    现在来定义两个函数:Add和Multi:

    //a和b相加
    int Add (int a, int b){
        return a + b ;
    }
    //a和b相乘
    int Multi (int a, int b){
        return a * b ;
    }

    现在我们可以写main函数,并且将函数指针指向正确的函数:

    int main (int argc , char **argv){
          STR str_obj;
          str_obj.opt = Add;    //函数指针变量指向Add函数
          str_obj. result = str_obj.opt(5,3);
          printf (" the result is %d
    ", str_obj.result );
          str_obj.opt= Multi;    //函数指针变量指向Multi函数 
          str_obj. result = str_obj.opt(5,3);
          printf (" the result is %d
    ", str_obj.result );
          return 0 ;
    }

    运行结果如下:

      the result is 8
      the result is 15 

    完整的代码如下:

    #include<stdio.h>
    
    typedef int (*Operation)(int a, int b);
    typedef struct _str {
        int result ; // to sotre the resut
        Operation  opt; // funtion pointer 
     } STR;
    
    //a和b相加
    int Add (int a, int b){
        return a + b ;
    }
    
    //a和b相乘
    int Multi (int a, int b){
        return a * b ;
    }
    
    int main (int argc , char **argv){
          STR str_obj;
          str_obj.opt = Add;    //函数指针变量指向Add函数
          str_obj. result = str_obj.opt(5,3);
          printf ("the result is %d
    ", str_obj.result );
          str_obj.opt= Multi;    //函数指针变量指向Multi函数 
          str_obj. result = str_obj.opt(5,3);
          printf ("the result is %d
    ", str_obj.result );
          return 0 ;
    }

     

  • 相关阅读:
    linux signal之初学篇
    Eclipse 每次打开workspace目录记录位置?
    [Clojure] A Room-Escape game, playing with telnet and pure-text commands
    孔雀翎----《Programming C# 》中国版 文章4版
    js一些编写的函数
    KVM,QEMU核心分析
    apche commons项目简介
    java基础—网络编程———建立聊天的形式
    学习算法
    css+html+js实现多级下拉和弹出菜单
  • 原文地址:https://www.cnblogs.com/wuyudong/p/function-pointer-in-c-struct.html
Copyright © 2020-2023  润新知