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 Réponses :
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;
Notez que FUNC1 CODE> et
FUNC2 code> ne renvoie aucune valeur, donc
COUT << (* VPTR) [0] () code> entraînera un comportement non défini
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;
}
Un pointeur sur un tableau n'est pas nécessaire ici. Un pointeur sur le premier élément de tableau fonctionne. Une référence à un tableau est également OK. P> FPTR (*vptr)[2];
vptr = arr;
// (*vptr)[0]() works
VPTR CODE> 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] () code>.
J'avais essayé ça, mais je ne pouvais pas comprendre pourquoi
(* vptr) [0] code> impression 1 toujours pour
[0] code> ou
[1] code> ou tout autre élément d'un tableau. Samways,
COUT << FUNC1 CODE> ou
COUT << & FUNC1 CODE> TOUJOURS
Si vous souhaitez imprimer un pointeur, vous devez lancer vers
Void * code> sinon
ostream :: opérateur << (bool) code> est appelé.
COUT << "\ N" << (NUR *) (* VPTR) [0] << endl; code>