zoukankan      html  css  js  c++  java
  • 函数指针数组的定义

    函数指针数组的定义方法,有两种:一种是标准的方法;一种是蒙骗法。

    第一种,标准方法:

    {
    分析:函数指针数组是一个其元素是函数指针的数组。那么也就是说,此数据结构是是一个数组,且其元素是一个指向函数入口地址的指针。
    根据分析:首先说明是一个数组:数组名[]
    其次,要说明其元素的数据类型指针:*数组名[].
    再 次,要明确这每一个数组元素是指向函数入口地址的指针:函数返回值类型 (*数组名[])().请注意,这里为什么要把“*数组名[]”用括号扩起来呢?因为圆括号和数组说明符的优先级是等同的,如果不用圆括号把指针数组说明 表达式扩起来,根据圆括号和方括号的结合方向,那么 *数组名[]() 说明的是什么呢?是元素返回值类型为指针的函数数组。有这样的函数数祖吗?不知道。所以必须括起来,以保证数组的每一个元素是指针。

    }

    第二种,蒙骗法:

    尽管函数不是变量,但它在内存中仍有其物理地址,该地址能够赋给指针变量。获取函数方法是:用不带有括号和参数的函数名得到。
    函数名相当于一个指向其函数入口指针常量。 那么既然函数名是一个指针常量,那么就可以对其进行一些相应的处理,如强制类型转换。
    那么我们就可以把这个地址放在一个整形指针数组中,然后作为函数指针调用即可。


    完整例子:
    #include "stdio.h"
    int add1(int a1,int b1);

    int add2(int a2,int b2);

    int main(int argc,char* argv[])

    {

    int numa1=1,numb1=2;

    int numa2=2,numb2=3;

    int (*op[2])(int a,int b);

    op[0]=add1;

    op[1]=add2;

    printf("%d %d ",op[0](numa1,numb1),op[1](numa2,numb2));

    getch();

    }

    int add1(int a1,int b1)

    {

    return a1+b1;

    }

    int add2(int a2,int b2)

    {

    return a2+b2;

    }


    再给出常用的C变量的定义方式:
    a) 一个整型数(An integer)
    b) 一个指向整型数的指针(A pointer to an integer)
    c) 一个指向指针的的指针,它指向的指针是指向一个整型数(A pointer to a pointer to an integer)
    d) 一个有10个整型数的数组(An array of 10 integers)
    e) 一个有10个指针的数组,该指针是指向一个整型数的(An array of 10 pointers to integers)
    f) 一个指向有10个整型数数组的指针(A pointer to an array of 10 integers)
    g) 一个指向函数的指针,该函数有一个整型参数并返回一个整型数(A pointer to a function that takes an integer as an argument and returns an integer)
    h) 一个有10个指针的数组,该指针指向一个函数,该函数有一个整型参数并返回一个整型数( An array of ten pointers to functions that take an integer argument and return an

    integer )

    答案是:
    a) int a; // An integer
    b) int *a; // A pointer to an integer
    c) int **a; // A pointer to a pointer to an integer
    d) int a[10]; // An array of 10 integers
    e) int *a[10]; // An array of 10 pointers to integers
    f) int (*a)[10]; // A pointer to an array of 10 integers
    g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer
    h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer

  • 相关阅读:
    【2020Python修炼记】web框架之 Django自带的序列化组件/form组件
    【2020Python修炼记】web框架之数据批量插入/分页器
    3.栈与队列
    2.链表
    1.数组
    越来越少人用JQuery,但你就不学了吗?(4)
    越来越少人用JQuery,但你就不学了吗?(3)
    越来越少人用JQuery,但你就不学了吗?(2)
    越来越少人用JQuery,但你就不学了吗?(1)
    JS事件、Bom对象和Dom对象(4)(乐字节架构)
  • 原文地址:https://www.cnblogs.com/xingrun/p/3372511.html
Copyright © 2011-2022 走看看