Function Pointer in C - GeeksforGeeks

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

1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesDangling,Void,NullandWildPointersAnUncommonrepresentationofarrayelementsHowtodeclareapointertoafunction?PointervsArrayinCvoidpointerinC/C++NULLpointerinCFunctionPointerinCWhatarenear,farandhugepointers?GenericLinkedListinCLinkedList|Set1(Introduction)LinkedList|Set2(Insertinganode)LinkedList|Set3(Deletinganode)DeleteaLinkedListnodeatagivenpositionWriteafunctiontodeleteaLinkedListFindLengthofaLinkedList(IterativeandRecursive)SearchanelementinaLinkedList(IterativeandRecursive)WriteafunctiontogetNthnodeinaLinkedListArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++WhatisMemoryLeak?Howcanweavoid?ConvertingStringstoNumbersinC/C++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++SubstringinC++DifferentMethodstoReverseaStringinC++CommandlineargumentsinC/C++Dangling,Void,NullandWildPointersAnUncommonrepresentationofarrayelementsHowtodeclareapointertoafunction?PointervsArrayinCvoidpointerinC/C++NULLpointerinCFunctionPointerinCWhatarenear,farandhugepointers?GenericLinkedListinCLinkedList|Set1(Introduction)LinkedList|Set2(Insertinganode)LinkedList|Set3(Deletinganode)DeleteaLinkedListnodeatagivenpositionWriteafunctiontodeleteaLinkedListFindLengthofaLinkedList(IterativeandRecursive)SearchanelementinaLinkedList(IterativeandRecursive)WriteafunctiontogetNthnodeinaLinkedListArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++WhatisMemoryLeak?Howcanweavoid?ConvertingStringstoNumbersinC/C++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++SubstringinC++DifferentMethodstoReverseaStringinC++CommandlineargumentsinC/C++FunctionPointerinCViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 05Sep,2018InC,likenormaldatapointers(int*,char*,etc),wecanhavepointerstofunctions.Followingisasimpleexamplethatshowsdeclarationandfunctioncallusingfunctionpointer.#include//Anormalfunctionwithanintparameter//andvoidreturntypevoidfun(inta){    printf("Valueofais%d\n",a);}  intmain(){    //fun_ptrisapointertofunctionfun()     void(*fun_ptr)(int)=&fun;      /*Theabovelineisequivalentoffollowingtwo       void(*fun_ptr)(int);       fun_ptr=&fun;     */      //Invokingfun()usingfun_ptr    (*fun_ptr)(10);      return0;}Output:Valueofais10Whydoweneedanextrabracketaroundfunctionpointerslikefun_ptrinaboveexample?Ifweremovebracket,thentheexpression“void(*fun_ptr)(int)”becomes“void*fun_ptr(int)”whichisdeclarationofafunctionthatreturnsvoidpointer.Seefollowingpostfordetails.Howtodeclareapointertoafunction?Followingaresomeinterestingfactsaboutfunctionpointers. 1)Unlikenormalpointers,afunctionpointerpointstocode,notdata.Typicallyafunctionpointerstoresthestartofexecutablecode.2)Unlikenormalpointers,wedonotallocatede-allocatememoryusingfunctionpointers. 3)Afunction’snamecanalsobeusedtogetfunctions’address.Forexample,inthebelowprogram,wehaveremovedaddressoperator‘&’inassignment.Wehavealsochangedfunctioncallbyremoving*,theprogramstillworks.#include//Anormalfunctionwithanintparameter//andvoidreturntypevoidfun(inta){    printf("Valueofais%d\n",a);}  intmain(){     void(*fun_ptr)(int)=fun; //&removed      fun_ptr(10); //*removed      return0;}Output:Valueofais10 4)Likenormalpointers,wecanhaveanarrayoffunctionpointers.Belowexampleinpoint5showssyntaxforarrayofpointers. 5)Functionpointercanbeusedinplaceofswitchcase.Forexample,inbelowprogram,userisaskedforachoicebetween0and2tododifferenttasks.#includevoidadd(inta,intb){    printf("Additionis%d\n",a+b);}voidsubtract(inta,intb){    printf("Subtractionis%d\n",a-b);}voidmultiply(inta,intb){    printf("Multiplicationis%d\n",a*b);}  intmain(){    //fun_ptr_arrisanarrayoffunctionpointers    void(*fun_ptr_arr[])(int,int)={add,subtract,multiply};    unsignedintch,a=15,b=10;      printf("EnterChoice:0foradd,1forsubtractand2"            "formultiply\n");    scanf("%d",&ch);      if(ch>2)return0;      (*fun_ptr_arr[ch])(a,b);      return0;} EnterChoice:0foradd,1forsubtractand2formultiply 2 Multiplicationis150 6)Likenormaldatapointers,afunctionpointercanbepassedasanargumentandcanalsobereturnedfromafunction.Forexample,considerthefollowingCprogramwherewrapper()receivesavoidfun()asparameterandcallsthepassedfunction.//AsimpleCprogramtoshowfunctionpointersasparameter#include  //Twosimplefunctionsvoidfun1(){printf("Fun1\n");}voidfun2(){printf("Fun2\n");}  //Afunctionthatreceivesasimplefunction//asparameterandcallsthefunctionvoidwrapper(void(*fun)()){    fun();}  intmain(){    wrapper(fun1);    wrapper(fun2);    return0;}ThispointinparticularisveryusefulinC.InC,wecanusefunctionpointerstoavoidcoderedundancy.Forexampleasimpleqsort()functioncanbeusedtosortarraysinascendingorderordescendingorbyanyotherorderincaseofarrayofstructures.Notonlythis,withfunctionpointersandvoidpointers,itispossibletouseqsortforanydatatype.//Anexampleforqsortandcomparator#include#include  //Asamplecomparatorfunctionthatisused//forsortinganintegerarrayinascendingorder.//Tosortanyarrayforanyotherdatatypeand/or//criteria,allweneedtodoiswritemorecompare//functions. Andwecanusethesameqsort()intcompare(constvoid*a,constvoid*b){  return(*(int*)a-*(int*)b);}  intmain(){  intarr[]={10,5,15,12,90,80};  intn=sizeof(arr)/sizeof(arr[0]),i;    qsort(arr,n,sizeof(int),compare);    for(i=0;i#include  //Acomparefunctionthatisusedforsearchinganinteger//arrayboolcompare(constvoid*a,constvoid*b){  return(*(int*)a==*(int*)b);}  //Generalpurposesearch()functionthatcanbeused//forsearchinganelement*xinanarrayarr[]of//arr_size.Notethatvoidpointersareusedsothat//thefunctioncanbecalledbypassingapointerof//anytype. ele_sizeissizeofanarrayelementintsearch(void*arr,intarr_size,intele_size,void*x,           boolcompare(constvoid*,constvoid*)){    //Sincechartakesonebyte,wecanusecharpointer    //foranytype/Togetpointerarithmeticcorrect,    //weneedtomultiplyindexwithsizeofanarray    //elementele_size    char*ptr=(char*)arr;      inti;    for(i=0;i



請為這篇文章評分?