C 如何使用函数指针数组?

C 如何使用函数指针数组?,c,initialization,function-pointers,C,Initialization,Function Pointers,我应该如何在C中使用函数指针数组 如何初始化它们?您有一个很好的示例,使用 要调用其中一个函数指针,请执行以下操作: result = (*p[op]) (i, j); // op being the index of one of the four functions void one( int a, int b){ printf(" \n[ ONE ] a = %d b = %d",a,b);} void two( int a, int b){ printf(" \n[

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

如何初始化它们?

您有一个很好的示例,使用

要调用其中一个函数指针,请执行以下操作:

result = (*p[op]) (i, j); // op being the index of one of the four functions
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;
}

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

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;
}

注意:在数组中,函数指针的编号将从0开始,与常规数组中的编号相同。因此,在上面的示例中,如果option=0,可以调用
fun1
,如果option=1,可以调用
fun2
,如果option=2,可以调用
fun3

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

例如,gtk_按钮的初始化


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},
...
因此,您可以按名称进入表并调用“关联”函数

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

问候

弗里德里希(Friedrich)

以下是如何使用它:

新乐趣 Main.c
#包括
#包括“New_Fun.h”
int main()
{
内部(*F_P)(内部y);
void(*F_A[5])()={F1,F2,F3,F4,F5};//如果它是int,指针不兼容肯定会发生
int-xyz,i;
printf(“Hello函数指针!\n”);
F_P=乐趣;
xyz=F_P(5);
printf(“值为%d\n”,xyz);
//(*F_A[5])={F1,F2,F3,F4,F5};
对于(i=0;i<5;i++)
{
F_A[i]();
}
printf(“\n\n”);
F_A[f1]();
F_A[f2]();
F_A[f3]();
F_A[f4]();
返回0;
}
我希望这有助于理解
函数指针。

这个“答案”更多的是对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; }

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

#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;
}
#包括
char*func1(char*a){
*a=‘b’;
返回a;
}
char*func2(char*a){
*a=‘c’;
返回a;
}
int main(){
字符a='a';
/*声明函数指针数组
*函数指针类型为char*name(char*)
*指向这种类型函数的指针应该是
*在名称前加*号,在*号周围加括号:
*字符*(*名称)(字符*)
*这些指针的数组与[x]相同
*/
char*(*函数[2])(char*)={func1,func2};
printf(“%c”,a);
/*这些函数返回一个指针,所以我需要修改指针
*这就是为什么括号前面有*的原因(以防把你弄糊涂了)
*/
printf(“%c,”,*(*函数[0])(&a));
printf(“%c\n”,*(*函数[1])(&a));
a=‘a’;
/*为函数指针类型创建“名称”
*funcp相当于类型char*(*funcname)(char*)
*/
typedef字符*(*funcp)(字符*);
/*现在,函数指针数组的声明
*变得容易
*/
funcp functions2[2]={func1,func2};
printf(“%c”,a);
printf(“%c,”,*(*functions2[0])(&a));
printf(“%c\n”,*(*functions2[1])(&a));
返回0;
}

这应该是一个简短、简单的复制粘贴上述响应的代码示例。希望这能有所帮助

#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);
}
#包括
使用名称空间std;
#定义DBG_PRINT(x)do{std::printf(“行:%-4d”“%15s=%-10d\n”,“行,#x,x);}而(0);
void F0(){printf(“printf%d\n”,0);}
void F1(){printf(“printf%d\n”,1);}
void F2(){printf(“printf%d\n”,2);}
void F3(){printf(“printf%d\n”,3);}
void F4(){printf(“printf%d\n”,4);}
void(*fArrVoid[N_FUNC])()={F0,F1,F2,F3,F4};
int和(inta,intb){返回(a+b);}
intsub(inta,intb){return(a-b);}
intmul(inta,intb){return(a*b);}
intdiv(inta,intb){return(a/b);}
int(*farrags[4])(inta,intb)={Sum,Sub,Mul,Div};
int main(){
对于(inti=0;i<5;i++)(*fArrVoid[i])();
printf(“\n”);
DBG_打印((*Farrags[0])(3,2))
DBG_打印((*Farrags[1])(3,2))
DBG_打印((*Farrags[2])(3,2))
DBG_打印((*Farrags[3])(3,2))
返回(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);}
无效三(inta,intb){printf(“\n[three]a=%d b=%d”,a,b);}
void four(inta,intb){printf(“\n[four]a=%d b=%d”,a,b);}
void five(inta,intb){printf(“\n[five]a=%d b=%d”,a,b);}
无效(*p[2][2])(整数,整数);
int main()
{
int i,j;
printf(“带函数指针的多维数组\n”);
p[0][0]=1;p[0][1]=2;p[1][0]=3;p[1][1]=4;
对于(i=1;i>=0;i--)

对于(j=0;j而言,最简单的解决方案是给出所需的最终向量的地址,并在函数内部对其进行修改

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
}

可以这样使用它:

//! 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);
//!定义:
#定义F_NUM 3
int(*p函数[F_NUM])(void*arg);
//!初始化:
int someFunction(void*arg){
int a=*((int*)arg);
返回a*a;
}
p函数[0]=someFunction;
//!使用:
int somethod(int idx,void*arg,int*result){
int done=0;
if(idx
下面是一个简单的示例,说明如何操作:

跳转表.c

intfunc1(intarg){返回arg+1;}
int func2(int arg){返回arg+2;
#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;
}
#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);
}
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;
}
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
}
//! 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);