如何使用函数指针数组?

问题描述 投票:0回答:13

我应该如何在 C 中使用函数指针数组?

如何初始化它们?

c initialization function-pointers
13个回答
269
投票

你有一个很好的例子这里(函数指针数组),其中详细的语法

int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);

int (*p[4]) (int x, int y);

int main(void)
{
  int result;
  int i, j, op;

  p[0] = sum; /* address of sum() */
  p[1] = subtract; /* address of subtract() */
  p[2] = mul; /* address of mul() */
  p[3] = div; /* address of div() */
[...]

调用这些函数指针之一:

result = (*p[op]) (i, j); // op being the index of one of the four functions

您还可以将

p
初始化为:

int (*p[4]) (int, int) = {sum, subtract, mul, div};

如:

#include <stdio.h>

// Function declarations
int sum(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int div(int a, int b) { return (b != 0) ? a / b : 0; }

int main() {
    // Array of function pointers initialization
    int (*p[4]) (int, int) = {sum, subtract, mul, div};

    // Using the function pointers
    int result;
    int i = 20, j = 5, op;

    for (op = 0; op < 4; op++) {
        result = p[op](i, j);
        printf("Result: %d\n", result);
    }

    return 0;
}

正如Gauthier评论

中所指出的那样

您可以通过指针调用函数而无需取消引用它。

有些人可能会争辩说,他们希望取消引用是明确的,这样他们就知道自己在处理什么。
其他人会回答说这是一个众所周知的习语,并且

p[op]()
没有更多的含义。

result = p[op](i, j);
有效

丹尼尔·海姆加特纳评论中确认

初始化指针数组

p[0] = sum
p[0] = &sum
是等效的。
同样,当调用函数(通过函数指针)时,您不需要取消引用
(*)
它:请参阅 Stack Overflow 问题“如何在不取消引用的情况下调用指向函数的指针?


60
投票

上述答案可能对您有帮助,但您可能还想知道如何使用函数指针数组。

void fun1()
{

}

void fun2()
{

}

void fun3()
{

}

void (*func_ptr[3])() = {fun1, fun2, fun3};

main()
{
    int option;


    printf("\nEnter function number you want");
    printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
    scanf("%d",&option);

    if((option>=0)&&(option<=2))
    { 
        (*func_ptr[option])();
    }

    return 0;
}

只能将具有相同返回类型和相同参数类型且没有参数的函数地址分配给单个函数指针数组。

如果上述所有函数都具有相同数量、相同类型的参数,您还可以像下面这样传递参数。

  (*func_ptr[option])(argu1);

注意:这里的数组中函数指针的编号将从0开始,与一般数组相同。所以在上面的例子中,如果 option=0 可以调用

fun1
,如果 option=1 可以调用
fun2
,如果 option=2 可以调用
fun3


11
投票

使用方法如下:

New_Fun.h

#ifndef NEW_FUN_H_
#define NEW_FUN_H_

#include <stdio.h>

typedef int speed;
speed fun(int x);

enum fp {
    f1, f2, f3, f4, f5
};

void F1();
void F2();
void F3();
void F4();
void F5();
#endif

New_Fun.c

#include "New_Fun.h"

speed fun(int x)
{
    int Vel;
    Vel = x;
    return Vel;
}

void F1()
{
    printf("From F1\n");
}

void F2()
{
    printf("From F2\n");
}

void F3()
{
    printf("From F3\n");
}

void F4()
{
    printf("From F4\n");
}

void F5()
{
    printf("From F5\n");
}

主.c

#include <stdio.h>
#include "New_Fun.h"

int main()
{
    int (*F_P)(int y);
    void (*F_A[5])() = { F1, F2, F3, F4, F5 };    // if it is int the pointer incompatible is bound to happen
    int xyz, i;

    printf("Hello Function Pointer!\n");
    F_P = fun;
    xyz = F_P(5);
    printf("The Value is %d\n", xyz);
    //(*F_A[5]) = { F1, F2, F3, F4, F5 };
    for (i = 0; i < 5; i++)
    {
        F_A[i]();
    }
    printf("\n\n");
    F_A[f1]();
    F_A[f2]();
    F_A[f3]();
    F_A[f4]();
    return 0;
}

我希望这有助于理解

Function Pointer.


9
投票

这个“答案”更多的是对VonC答案的补充;只需注意可以通过 typedef 简化语法,并且可以使用聚合初始化:

typedef int FUNC(int, int);

FUNC sum, subtract, mul, div;
FUNC *p[4] = { sum, subtract, mul, div };

int main(void)
{
    int result;
    int i = 2, j = 3, op = 2;  // 2: mul

    result = p[op](i, j);   // = 6
}

// maybe even in another file
int sum(int a, int b) { return a+b; }
int subtract(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int div(int a, int b) { return a/b; }

5
投票

这里有一个更简单的示例来说明如何做到这一点:

jump_table.c

int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5, 
                               func6, func7, func8, func9, func10 };
    
int main(void) {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

数组中存储的所有函数必须具有相同的签名。这仅仅意味着它们必须返回相同的类型(例如

int
)并具有相同的参数(上面示例中的单个
int
)。


在 C++ 中,您可以对 static 类方法(但不能是实例方法)执行相同的操作。例如,您可以在上面的数组中使用

MyClass::myStaticMethod
,但不能使用
MyClass::myInstanceMethod
instance.myInstanceMethod
:

class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

2
投票

哦,有很多例子。只要看看 glib 或 gtk 中的任何内容即可。 你可以在那里看到函数指针的工作原理。

这里例如 gtk_button 的初始化。


static void
gtk_button_class_init (GtkButtonClass *klass)
{
  GObjectClass *gobject_class;
  GtkObjectClass *object_class;
  GtkWidgetClass *widget_class;
  GtkContainerClass *container_class;

  gobject_class = G_OBJECT_CLASS (klass);
  object_class = (GtkObjectClass*) klass;
  widget_class = (GtkWidgetClass*) klass;
  container_class = (GtkContainerClass*) klass;

  gobject_class->constructor = gtk_button_constructor;
  gobject_class->set_property = gtk_button_set_property;
  gobject_class->get_property = gtk_button_get_property;

在 gtkobject.h 中您可以找到以下声明:


struct _GtkObjectClass
{
  GInitiallyUnownedClass parent_class;

  /* Non overridable class methods to set and get per class arguments */
  void (*set_arg) (GtkObject *object,
           GtkArg    *arg,
           guint      arg_id);
  void (*get_arg) (GtkObject *object,
           GtkArg    *arg,
           guint      arg_id);

  /* Default signal handler for the ::destroy signal, which is
   *  invoked to request that references to the widget be dropped.
   *  If an object class overrides destroy() in order to perform class
   *  specific destruction then it must still invoke its superclass'
   *  implementation of the method after it is finished with its
   *  own cleanup. (See gtk_widget_real_destroy() for an example of
   *  how to do this).
   */
  void (*destroy)  (GtkObject *object);
};

(*set_arg) 是一个指向函数的指针,例如可以在某个派生类中为其分配另一个实现。

你经常会看到这样的事情

struct function_table {
   char *name;
   void (*some_fun)(int arg1, double arg2);
};

void function1(int  arg1, double arg2)....


struct function_table my_table [] = {
    {"function1", function1},
...

因此您可以通过名称进入表并调用“关联”函数。

或者您可能使用哈希表,将函数放入其中并“按名称”调用它。

问候
弗里德里希


2
投票

可以这样使用:

//! Define:
#define F_NUM 3
int (*pFunctions[F_NUM])(void * arg);

//! Initialise:
int someFunction(void * arg) {
    int a= *((int*)arg);
    return a*a;
}

pFunctions[0]= someFunction;

//! Use:
int someMethod(int idx, void * arg, int * result) {
    int done= 0;
    if (idx < F_NUM && pFunctions[idx] != NULL) {
        *result= pFunctions[idx](arg);
        done= 1;
    }
    return done;
}

int x= 2;
int z= 0;
someMethod(0, (void*)&x, &z);
assert(z == 4);

1
投票

这应该是上述响应的简短复制和粘贴代码示例。希望这会有所帮助。

#include <iostream>
using namespace std;

#define DBG_PRINT(x) do { std::printf("Line:%-4d" "  %15s = %-10d\n", __LINE__, #x, x); } while(0);

void F0(){ printf("Print F%d\n", 0); }
void F1(){ printf("Print F%d\n", 1); }
void F2(){ printf("Print F%d\n", 2); }
void F3(){ printf("Print F%d\n", 3); }
void F4(){ printf("Print F%d\n", 4); }
void (*fArrVoid[N_FUNC])() = {F0, F1, F2, F3, F4};

int Sum(int a, int b){ return(a+b); }
int Sub(int a, int b){ return(a-b); }
int Mul(int a, int b){ return(a*b); }
int Div(int a, int b){ return(a/b); }
int (*fArrArgs[4])(int a, int b) = {Sum, Sub, Mul, Div};

int main(){
    for(int i = 0; i < 5; i++)  (*fArrVoid[i])();
    printf("\n");

    DBG_PRINT((*fArrArgs[0])(3,2))
    DBG_PRINT((*fArrArgs[1])(3,2))
    DBG_PRINT((*fArrArgs[2])(3,2))
    DBG_PRINT((*fArrArgs[3])(3,2))

    return(0);
}

1
投票

最简单的解决方案是给出你想要的最终向量的地址,并在函数内部修改它。

void calculation(double result[] ){  //do the calculation on result

   result[0] = 10+5;
   result[1] = 10 +6;
   .....
}

int main(){

    double result[10] = {0}; //this is the vector of the results

    calculation(result);  //this will modify result
}

0
投票

这个问题已经用很好的例子回答了。唯一可能缺少的示例是函数返回指针的示例。我用这个写了另一个例子,并添加了很多评论,以防有人觉得有帮助:

#include <stdio.h>

char * func1(char *a) {
    *a = 'b';
    return a;
}

char * func2(char *a) {
    *a = 'c';
    return a;
}

int main() {
    char a = 'a';
    /* declare array of function pointers
     * the function pointer types are char * name(char *)
     * A pointer to this type of function would be just
     * put * before name, and parenthesis around *name:
     *   char * (*name)(char *)
     * An array of these pointers is the same with [x]
     */
    char * (*functions[2])(char *) = {func1, func2};
    printf("%c, ", a);
    /* the functions return a pointer, so I need to deference pointer
     * Thats why the * in front of the parenthesis (in case it confused you)
     */
    printf("%c, ", *(*functions[0])(&a)); 
    printf("%c\n", *(*functions[1])(&a));

    a = 'a';
    /* creating 'name' for a function pointer type
     * funcp is equivalent to type char *(*funcname)(char *)
     */
    typedef char *(*funcp)(char *);
    /* Now the declaration of the array of function pointers
     * becomes easier
     */
    funcp functions2[2] = {func1, func2};

    printf("%c, ", a);
    printf("%c, ", *(*functions2[0])(&a));
    printf("%c\n", *(*functions2[1])(&a));

    return 0;
}

0
投票

这个带有函数指针的多维数组的简单示例“:

void one( int a, int b){    printf(" \n[ ONE ]  a =  %d   b = %d",a,b);}
void two( int a, int b){    printf(" \n[ TWO ]  a =  %d   b = %d",a,b);}
void three( int a, int b){    printf("\n [ THREE ]  a =  %d   b = %d",a,b);}
void four( int a, int b){    printf(" \n[ FOUR ]  a =  %d   b = %d",a,b);}
void five( int a, int b){    printf(" \n [ FIVE ]  a =  %d   b = %d",a,b);}
void(*p[2][2])(int,int)   ;
int main()
{
    int i,j;
    printf("multidimensional array with function pointers\n");

    p[0][0] = one;    p[0][1] = two;    p[1][0] = three;    p[1][1] = four;
    for (  i  = 1 ; i >=0; i--)
        for (  j  = 0 ; j <2; j++)
            (*p[i][j])( (i, i*j);
    return 0;
}

0
投票

这里是使用指针数组调用具有不同签名的函数的示例代码。

#include<stdio.h>

#define TOTAL_FUNCTIONS 3

#define FUNCTION_ADD 0
#define FUNCTION_SUBTRACT 1
#define FUNCTION_MULTIPLY 2

int funcAdd(int a, int b, int c)
{
    return a+b+c;
}

void funcSubtract(int a, int b)
{
    printf("\nDiffrence = %d\n",a*b);
}

int funcMultiply(int a, int b)
{
    return a*b;
}


int main()
{
    void* funPtr[3] = {funcAdd, funcSubtract, funcMultiply};

    int result = 0;
    int index = 0;
    while(index < TOTAL_FUNCTIONS){
        switch(index){
            case FUNCTION_ADD:
                result = ((int (*)(int, int, int))funPtr[FUNCTION_ADD])(2,3,4);
                printf("\nSum = %d\n", result);
                break;
            case FUNCTION_SUBTRACT:
                ((void (*)(int, int))funPtr[FUNCTION_SUBTRACT])(5,3);
                break;
            case FUNCTION_MULTIPLY:
                result = ((int (*)(int, int))funPtr[FUNCTION_MULTIPLY])(2,3);
                printf("\nProduct %d\n", result);
                break;
            default:
                break;
        }
        ++index;
    }

    return 0;
}

-2
投票
#include <iostream>
using namespace std;
    
int sum (int , int);
int prod (int , int);
    
int main()
{
    int (*p[2])(int , int ) = {sum,prod};
    
    cout << (*p[0])(2,3) << endl;
    cout << (*p[1])(2,3) << endl;
}
    
int sum (int a , int b)
{
    return a+b;
}
    
int prod (int a, int b)
{
    return a*b;
}
© www.soinside.com 2019 - 2024. All rights reserved.