通过指向函数指针数组的指针调用函数

Calling a function through pointer to an array of function pointers

我试图理解通过指向函数指针数组的指针调用函数的语法。 我有函数指针数组 FPTR arr[2] 和指向该数组的指针 FPTR (vptr)[2] 。但是当试图通过指向数组的指针调用时它给了我一个错误

typedef int (*FPTR)();
int func1(){
        cout<<"func1() being called\n";
}
int func2(){
        cout<<"fun2() being called\n";
}

    FPTR arr[2] = {&func1,&func2};

    FPTR (*vptr)[2];
    vptr=&arr;

    cout<<"\n"<<vptr[0]<<endl;
    cout<<"\n"<<vptr[0]()<<endl;  // ERROR  when trying to call the first function
typedef int (*FPTR)();
int func1(){
        cout<<"func1() being called\n";
        return 1;

}
int func2(){
        cout<<"fun2() being called\n";
        return 2;
}

FPTR arr[2] = {func1, func2}; 

// call both methods via array of pointers
cout<<"\n"<< arr[0]() <<endl;
cout<<"\n"<< arr[1]() <<endl;

FPTR (*vptr)[2] = &arr;

// call both methods via pointer to array of pointers
cout<<"\n"<< vptr[0][0]() <<endl;
cout<<"\n"<< vptr[0][1]() <<endl;

// or... 
cout<<"\n"<< (*vptr)[0]() <<endl;
cout<<"\n"<< (*vptr)[1]() <<endl;

vptr 是指向数组的 指针 ,因此您必须取消引用它才能使用该数组。

#include <iostream>
using std::cout;
using std::endl;

typedef int (*FPTR)();
int func1(){
        cout<<"func1() being called\n";
        return 0;
}
int func2(){
        cout<<"fun2() being called\n";
        return 2;
}

int main(){
    FPTR arr[2] = {&func1,&func2};

    FPTR (*vptr)[2];
    vptr=&arr;

    cout<<"\n"<<vptr[0]<<endl;
    cout<<"\n"<<(*vptr)[0]()<<endl;
}

live example

请注意 func1()func2() 必须 return 值,否则输出它们的结果会导致未定义的行为

此处不需要指向数组的指针。指向第一个数组元素的指针有效。

FPTR *vptr;
vptr = arr;

// vptr[0]() works

引用数组也可以。

FPTR (&vptr)[2] = arr;

// vptr[0]() still works

如果出于某种原因你需要一个指向数组的指针,你可以:

FPTR (*vptr)[2];
vptr = arr;

// (*vptr)[0]() works

为避免混淆,std::array 优于普通数组。