How can I use an array of function pointers? - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HowcanIuseanarrayoffunctionpointers? AskQuestion Asked 13years,8monthsago Modified 11monthsago Viewed 330ktimes 194 86 HowshouldIusearrayoffunctionpointersinC? HowcanIinitializethem? cinitializationfunction-pointers Share Follow editedMay21,2014at21:43 TheGuywithTheHat 10.3k88goldbadges5959silverbadges7373bronzebadges askedOct31,2008at6:45 johnjohn Addacomment  |  12Answers 12 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 250 Youhaveagoodexamplehere(ArrayofFunctionpointers),withthesyntaxdetailed. intsum(inta,intb); intsubtract(inta,intb); intmul(inta,intb); intdiv(inta,intb); int(*p[4])(intx,inty); intmain(void) { intresult; inti,j,op; p[0]=sum;/*addressofsum()*/ p[1]=subtract;/*addressofsubtract()*/ p[2]=mul;/*addressofmul()*/ p[3]=div;/*addressofdiv()*/ [...] Tocalloneofthosefunctionpointers: result=(*p[op])(i,j);//opbeingtheindexofoneofthefourfunctions Share Follow editedOct31,2008at19:37 answeredOct31,2008at6:48 VonCVonC 1.1m481481goldbadges40604060silverbadges47854785bronzebadges 9 3 Goodanswer-youshouldextendittoshowhowtocalloneofthefunctions,though. – JonathanLeffler Oct31,2008at19:30 2 @crucifiedsoul"theCProgrammingLanguage"writtenbyBrianKernighanandDennisRitchie?Itcouldbe,butIdidn'thaveitasareferenceatthetimeIwrotetheanswerthreeandanhalfyearago.SoIdon'tknow. – VonC Mar30,2012at1:51 24 I'dliketoaddyoucaninitializepwith(*p[4])(int,int){sum,substract,mul,div} – jiggunjer Jul7,2015at8:04 2 @VonC:greatanswer.+1forthelinks. – Destructor Jul9,2015at17:04 1 @WilliamMartensYouarewelcome.IamalwayssurprisedwhenalinkIused12+yearsagoisstillworking! – VonC Feb17,2021at9:33  |  Show4morecomments 58 Theaboveanswersmayhelpyoubutyoumayalsowanttoknowhowtousearrayoffunctionpointers. voidfun1() { } voidfun2() { } voidfun3() { } void(*func_ptr[3])()={fun1,fun2,fun3}; main() { intoption; printf("\nEnterfunctionnumberyouwant"); printf("\nYoushouldnotenterotherthan0,1,2");/*becausewehaveonly3functions*/ scanf("%d",&option); if((option>=0)&&(option<=2)) { (*func_ptr[option])(); } return0; } Youcanonlyassigntheaddressesoffunctionswiththesamereturntypeandsameargumenttypesandnoofargumentstoasinglefunctionpointerarray. Youcanalsopassargumentslikebelowifalltheabovefunctionsarehavingthesamenumberofargumentsofsametype. (*func_ptr[option])(argu1); Note:hereinthearraythenumberingofthefunctionpointerswillbestartingfrom0sameasingeneralarrays.Soinaboveexamplefun1canbecalledifoption=0,fun2canbecalledifoption=1andfun3canbecalledifoption=2. Share Follow editedJan23,2020at6:29 RayHulha 9,87355goldbadges4949silverbadges5050bronzebadges answeredOct31,2008at6:51 ManojDoubtsManojDoubts 12.8k1515goldbadges4040silverbadges4444bronzebadges 2 Evenforthislittledemo,youshouldaddacheckfortheinputvalue,sincecodetargetsanewbie...:-) – PhiLho Oct31,2008at6:53 Don'tforget#includeattopfornewbieslikeme – www-0av-Com Jan31at13:22 Addacomment  |  11 Here'showyoucanuseit: New_Fun.h #ifndefNEW_FUN_H_ #defineNEW_FUN_H_ #include typedefintspeed; speedfun(intx); enumfp{ f1,f2,f3,f4,f5 }; voidF1(); voidF2(); voidF3(); voidF4(); voidF5(); #endif New_Fun.c #include"New_Fun.h" speedfun(intx) { intVel; Vel=x; returnVel; } voidF1() { printf("FromF1\n"); } voidF2() { printf("FromF2\n"); } voidF3() { printf("FromF3\n"); } voidF4() { printf("FromF4\n"); } voidF5() { printf("FromF5\n"); } Main.c #include #include"New_Fun.h" intmain() { int(*F_P)(inty); void(*F_A[5])()={F1,F2,F3,F4,F5};//ifitisintthepointerincompatibleisboundtohappen intxyz,i; printf("HelloFunctionPointer!\n"); F_P=fun; xyz=F_P(5); printf("TheValueis%d\n",xyz); //(*F_A[5])={F1,F2,F3,F4,F5}; for(i=0;i<5;i++) { F_A[i](); } printf("\n\n"); F_A[f1](); F_A[f2](); F_A[f3](); F_A[f4](); return0; } IhopethishelpsinunderstandingFunctionPointer. Share Follow editedFeb15,2017at17:49 answeredMay22,2012at11:07 RasmiRanjanNayakRasmiRanjanNayak 10.9k2828goldbadges7979silverbadges119119bronzebadges 3 Line15ofMain.cshouldbefor(i=0;i<5;i++),right? – user3116936 Jan14,2017at3:40 1 Whydidyoudeclarethefpenumerator? – Arrrow Sep18,2017at12:50 @Arrrow:IthinkIsawsomeofthelegacycodewheretheymadeitinthatway...Anditlooksverybeautiful.Justremovef1,f2...andinplaceofthenenter'writefile,readfromfile...'...itbecomesmoreredable – RasmiRanjanNayak Nov13,2017at21:06 Addacomment  |  8 This"answer"ismoreofanaddendumtoVonC'sanswer;justnotingthatthesyntaxcanbesimplifiedviaatypedef,andaggregateinitializationcanbeused: typedefintFUNC(int,int); FUNCsum,subtract,mul,div; FUNC*p[4]={sum,subtract,mul,div}; intmain(void) { intresult; inti=2,j=3,op=2;//2:mul result=p[op](i,j);//=6 } //maybeeveninanotherfile intsum(inta,intb){returna+b;} intsubtract(inta,intb){returna-b;} intmul(inta,intb){returna*b;} intdiv(inta,intb){returna/b;} Share Follow answeredMay28,2014at5:04 M.MM.M 135k2121goldbadges190190silverbadges336336bronzebadges 1 1 Pleasereserveallcapstopre-processormacros.Manywouldalsoadvocatecreatedtypetoendwith_t,althoughthisseemscontroversialforuserdefinedtypes. – Gauthier May24,2021at12:49 Addacomment  |  4 Here'sasimplerexampleofhowtodoit: jump_table.c intfunc1(intarg){returnarg+1;} intfunc2(intarg){returnarg+2;} intfunc3(intarg){returnarg+3;} intfunc4(intarg){returnarg+4;} intfunc5(intarg){returnarg+5;} intfunc6(intarg){returnarg+6;} intfunc7(intarg){returnarg+7;} intfunc8(intarg){returnarg+8;} intfunc9(intarg){returnarg+9;} intfunc10(intarg){returnarg+10;} int(*jump_table[10])(int)={func1,func2,func3,func4,func5, func6,func7,func8,func9,func10}; intmain(void){ intindex=2; intargument=42; intresult=(*jump_table[index])(argument); //resultis45 } Allfunctionsstoredinthearraymusthavethesamesignature.Thissimplymeansthattheymustreturnthesametype(e.g.int)andhavethesamearguments(asingleintintheexampleabove). InC++,youcandothesamewithstaticclassmethods(butnotinstancemethods).ForexampleyoucoulduseMyClass::myStaticMethodinthearrayabovebutnotMyClass::myInstanceMethodnorinstance.myInstanceMethod: classMyClass{ public: staticintmyStaticMethod(intfoo){returnfoo+17;} intmyInstanceMethod(intbar){returnbar+17;} } MyClassinstance; Share Follow editedMar2,2021at23:12 answeredMar2,2021at22:45 AlexHajnalAlexHajnal 22111silverbadge88bronzebadges Addacomment  |  2 Oh,therearetonsofexample.Justhavealookatanythingwithingliborgtk. Youcanseetheworkoffunctionpointersinworktherealltheway. Heree.gtheinitializationofthegtk_buttonstuff. staticvoid gtk_button_class_init(GtkButtonClass*klass) { GObjectClass*gobject_class; GtkObjectClass*object_class; GtkWidgetClass*widget_class; GtkContainerClass*container_class; gobject_class=G_OBJECT_CLASS(klass); object_class=(GtkObjectClass*)klass; widget_class=(GtkWidgetClass*)klass; container_class=(GtkContainerClass*)klass; gobject_class->constructor=gtk_button_constructor; gobject_class->set_property=gtk_button_set_property; gobject_class->get_property=gtk_button_get_property; Andingtkobject.hyoufindthefollowingdeclarations: struct_GtkObjectClass { GInitiallyUnownedClassparent_class; /*Nonoverridableclassmethodstosetandgetperclassarguments*/ void(*set_arg)(GtkObject*object, GtkArg*arg, guintarg_id); void(*get_arg)(GtkObject*object, GtkArg*arg, guintarg_id); /*Defaultsignalhandlerforthe::destroysignal,whichis *invokedtorequestthatreferencestothewidgetbedropped. *Ifanobjectclassoverridesdestroy()inordertoperformclass *specificdestructionthenitmuststillinvokeitssuperclass' *implementationofthemethodafteritisfinishedwithits *owncleanup.(Seegtk_widget_real_destroy()foranexampleof *howtodothis). */ void(*destroy)(GtkObject*object); }; The(*set_arg)stuffisapointertofunctionandthiscane.gbeassignedanotherimplementationinsomederivedclass. Oftenyouseesomethinglikethis structfunction_table{ char*name; void(*some_fun)(intarg1,doublearg2); }; voidfunction1(intarg1,doublearg2).... structfunction_tablemy_table[]={ {"function1",function1}, ... Soyoucanreachintothetablebynameandcallthe"associated"function. Ormaybeyouuseahashtableinwhichyouputthefunctionandcallit"byname". Regards Friedrich Share Follow editedOct31,2008at19:29 JonathanLeffler 700k130130goldbadges862862silverbadges12311231bronzebadges answeredOct31,2008at6:54 FriedrichFriedrich 5,8282424silverbadges4444bronzebadges 1 Woulditbepssibletousesuchafunction_tableforhashingfunctionswithinthehashtableimplementationitself?(Read:circulardependecyinvolved). – Flavius Dec1,2009at12:50 Addacomment  |  2 Canuseitinthewaylikethis: //!Define: #defineF_NUM3 int(*pFunctions[F_NUM])(void*arg); //!Initialise: intsomeFunction(void*arg){ inta=*((int*)arg); returna*a; } pFunctions[0]=someFunction; //!Use: intsomeMethod(intidx,void*arg,int*result){ intdone=0; if(idx usingnamespacestd; #defineDBG_PRINT(x)do{std::printf("Line:%-4d""%15s=%-10d\n",__LINE__,#x,x);}while(0); voidF0(){printf("PrintF%d\n",0);} voidF1(){printf("PrintF%d\n",1);} voidF2(){printf("PrintF%d\n",2);} voidF3(){printf("PrintF%d\n",3);} voidF4(){printf("PrintF%d\n",4);} void(*fArrVoid[N_FUNC])()={F0,F1,F2,F3,F4}; intSum(inta,intb){return(a+b);} intSub(inta,intb){return(a-b);} intMul(inta,intb){return(a*b);} intDiv(inta,intb){return(a/b);} int(*fArrArgs[4])(inta,intb)={Sum,Sub,Mul,Div}; intmain(){ for(inti=0;i<5;i++)(*fArrVoid[i])(); printf("\n"); DBG_PRINT((*fArrArgs[0])(3,2)) DBG_PRINT((*fArrArgs[1])(3,2)) DBG_PRINT((*fArrArgs[2])(3,2)) DBG_PRINT((*fArrArgs[3])(3,2)) return(0); } Share Follow answeredJul28,2016at14:43 nimig18nimig18 66777silverbadges99bronzebadges 2 Ifitisacopy&pastefromotheranwers,I'mnotsureitaddsanyvalue... – FabiosaysReinstateMonica Jul28,2016at15:12 YesIseeyourpoint,Iwilladdthevaluetonightcurrentlyatwork. – nimig18 Jul29,2016at18:15 Addacomment  |  1 Thesimplestsolutionistogivetheaddressofthefinalvectoryouwant,andmodifyitinsidethefunction. voidcalculation(doubleresult[]){//dothecalculationonresult result[0]=10+5; result[1]=10+6; ..... } intmain(){ doubleresult[10]={0};//thisisthevectoroftheresults calculation(result);//thiswillmodifyresult } Share Follow editedFeb6,2017at17:06 MikeP 7011313silverbadges2626bronzebadges answeredFeb6,2017at15:00 LeonardoLeonardo 1111bronzebadge Addacomment  |  0 Thisquestionhasbeenalreadyansweredwithverygoodexamples.Theonlyexamplethatmightbemissingisonewherethefunctionsreturnpointers.Iwroteanotherexamplewiththis,andaddedlotsofcomments,incasesomeonefindsithelpful: #include char*func1(char*a){ *a='b'; returna; } char*func2(char*a){ *a='c'; returna; } intmain(){ chara='a'; /*declarearrayoffunctionpointers *thefunctionpointertypesarechar*name(char*) *Apointertothistypeoffunctionwouldbejust *put*beforename,andparenthesisaround*name: *char*(*name)(char*) *Anarrayofthesepointersisthesamewith[x] */ char*(*functions[2])(char*)={func1,func2}; printf("%c,",a); /*thefunctionsreturnapointer,soIneedtodeferencepointer *Thatswhythe*infrontoftheparenthesis(incaseitconfusedyou) */ printf("%c,",*(*functions[0])(&a)); printf("%c\n",*(*functions[1])(&a)); a='a'; /*creating'name'forafunctionpointertype *funcpisequivalenttotypechar*(*funcname)(char*) */ typedefchar*(*funcp)(char*); /*Nowthedeclarationofthearrayoffunctionpointers *becomeseasier */ funcpfunctions2[2]={func1,func2}; printf("%c,",a); printf("%c,",*(*functions2[0])(&a)); printf("%c\n",*(*functions2[1])(&a)); return0; } Share Follow answeredMay31,2016at18:22 JayMedinaJayMedina 49455silverbadges1111bronzebadges Addacomment  |  0 Thissimpleexampleformultidimensionalarraywithfunctionpointers": voidone(inta,intb){printf("\n[ONE]a=%db=%d",a,b);} voidtwo(inta,intb){printf("\n[TWO]a=%db=%d",a,b);} voidthree(inta,intb){printf("\n[THREE]a=%db=%d",a,b);} voidfour(inta,intb){printf("\n[FOUR]a=%db=%d",a,b);} voidfive(inta,intb){printf("\n[FIVE]a=%db=%d",a,b);} void(*p[2][2])(int,int); intmain() { inti,j; printf("multidimensionalarraywithfunctionpointers\n"); p[0][0]=one;p[0][1]=two;p[1][0]=three;p[1][1]=four; for(i=1;i>=0;i--) for(j=0;j<2;j++) (*p[i][j])((i,i*j); return0; } Share Follow answeredDec29,2016at7:11 arunkumararunkumar 3644bronzebadges Addacomment  |  -1 #include usingnamespacestd; intsum(int,int); intprod(int,int); intmain() { int(*p[2])(int,int)={sum,prod}; cout<



請為這篇文章評分?