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

时间:2019-09-09 05:06:08

标签: c++ function-pointers

我试图理解通过指向函数指针数组的指针调用函数的语法。 我有一组函数指针hover和一个指向该数组FPTR arr[2]的指针。但这在尝试通过指向数组的指针调用时给了我一个错误

FPTR (vptr)[2]

3 个答案:

答案 0 :(得分:5)

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()必须返回值,否则输出结果将导致未定义的行为

答案 1 :(得分:2)

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;

答案 2 :(得分:2)

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

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替换为普通数组。