0
votes

Appeler une fonction via un pointeur sur un tableau de pointeurs de la fonction

J'essaie de comprendre la syntaxe d'appeler la fonction via un pointeur sur un tableau de pointeurs de fonction. J'ai une gamme de pointeurs de fonction fptr arr [2] code> et un pointeur sur ce tableau FPTR (VPTR) [2] code>. Mais cela me donne une erreur lorsque vous essayez d'appeler le pointeur sur un tableau

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


3 commentaires

VPTR est le pointeur, vous devez donc d'abord la désarférence avant d'accéder aux éléments de matrice pointée par celui-ci: (* VPTR) [0] () .


J'avais essayé ça, mais je ne pouvais pas comprendre pourquoi (* vptr) [0] impression 1 toujours pour [0] ou [1] ou tout autre élément d'un tableau. Samways, COUT << FUNC1 ou COUT << & FUNC1 TOUJOURS


Si vous souhaitez imprimer un pointeur, vous devez lancer vers Void * sinon ostream :: opérateur << (bool) est appelé. COUT << "\ N" << (NUR *) (* VPTR) [0] << endl;


3 Réponses :


2
votes
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;


1 commentaires

Notez que FUNC1 et FUNC2 ne renvoie aucune valeur, donc COUT << (* VPTR) [0] () entraînera un comportement non défini



5
votes

vptr code> est pointeur em> à un tableau, vous devez donc la désirer pour utiliser la matrice.

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


0 commentaires

2
votes

Un pointeur sur un tableau n'est pas nécessaire ici. Un pointeur sur le premier élément de tableau fonctionne. XXX PRE>

Une référence à un tableau est également OK. P>

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

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


0 commentaires