簡體   English   中英

通過指向函數指針數組的指針調用函數

[英]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

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

現場例子

注意func1()func2()必須返回值,否則輸出它們的結果將導致未定義的行為

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;

這里不需要指向數組的指針。 指向第一個數組元素的指針起作用。

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為純數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM