C function Pointer - javatpoint

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

Function pointers are used in those applications where we do not know in advance which function will be called. In an array of function pointers, array takes ... ⇧SCROLLTOTOP Home C C++ C# Java SQL HTML CSS JavaScript XML Ajax Android Cloud DesignPattern Quiz Projects InterviewQ Comment Forum CTutorial WhatisCLanguage HistoryofC FeaturesofC HowtoinstallC FirstCProgram CompilationProcessinC printfscanf VariablesinC DataTypesinc Keywordsinc CIdentifiers COperators CComments CFormatSpecifier CEscapeSequence ASCIIvalueinC ConstantsinC LiteralsinC TokensinC CBoolean StaticinC ProgrammingErrorsinC CompiletimevsRuntime ConditionalOperatorinC BitwiseOperatorinC 2scomplementinC CFundamentalTest CControlStatements Cif-else Cswitch if-elsevsswitch CLoops Cdo-whileloop Cwhileloop Cforloop NestedLoopsinC InfiniteLoopinC Cbreak Ccontinue Cgoto TypeCasting CControlStatementTest CFunctions Whatisfunction Call:Value&Reference Recursioninc StorageClasses CFunctionsTest CArray 1-DArray 2-DArray ReturnanArrayinC ArraytoFunction CArrayTest CPointers CPointers CPointertoPointer CPointerArithmetic DanglingPointersinC sizeof()operatorinC constPointerinC voidpointerinC CDereferencePointer NullPointerinC CFunctionPointer FunctionpointerasargumentinC CPointersTest CDynamicMemory Dynamicmemory CStrings StringinC Cgets()&puts() CStringFunctions Cstrlen() Cstrcpy() Cstrcat() Cstrcmp() Cstrrev() Cstrlwr() Cstrupr() Cstrstr() CStringTest CMath CMathFunctions CStructureUnion CStructure typedefinC CArrayofStructures CNestedStructure StructurePaddinginC CUnion CStructureTest CFileHandling CFileHandling Cfprintf()fscanf() Cfputc()fgetc() Cfputs()fgets() Cfseek() Crewind() Cftell() CPreprocessor CPreprocessor CMacros C#include C#define C#undef C#ifdef C#ifndef C#if C#else C#error C#pragma CPreprocessorTest CCommandLine CommandLineArguments CMisc CExpressions DataSegments FlowofCProgram ClassificationofProgrammingLanguages EnuminC Whatisgetch()inC WhatisthefunctioncallinC typedefvsdefineinC CProgrammingTest CProgrammingTest CPrograms Top10+CPrograms FibonacciSeries PrimeNumber PalindromeNumber Cprogramtocomparethetwostrings StringsConcatenationinC Factorial ArmstrongNumber Sumofdigits CountthenumberofdigitsinC ReverseNumber SwapNumber Print"Hello"without; AssemblycodeinC Cprogramwithoutmain MatrixMultiplication DecimaltoBinary NumberinCharacters AlphabetTriangle NumberTriangle FibonacciTriangle HexadecimaltoBinary HexadecimaltoDecimal OctaltoHexadecimalinC StrongnumberinC StarPrograminC itoaFunctioninC ExtraLongFactorialsinC LeapyearprograminC PerfectNumberPrograminC VariablesvsConstants RoundRobinPrograminCwithOutput CProgramtofindtherootsofquadraticequation TypeCastingvsTypeConversion HowtorunaCprograminVisualStudioCode ModulusOperatorinC/C++ SumoffirstNnaturalnumbersinC BigONotationinC LCMoftwonumbersinC whileloopvsdo-whileloopinC MemoryLayoutinC BalancedParenthesisinC BinarytoDecimalNumberinC GCDoftwonumbersinC Getchar()functioninC flowchartinC SimpsonMethod PyramidPatternsinC RandomFunctioninC Floyd'sTriangleinC CHeaderFiles abs()functioninC Atoi()functioninC StructurePointerinC sprintf()inC RangeofIntinC CProgramtoconvert24Hourtimeto12Hourtime WhatisdoubleinC WhatisthemaininC CalculatorPrograminC CallocinC user-definedvslibraryfunctioninC MemsetC ASCIITableinC StaticfunctioninC ReverseaStringinC TwinPrimeNumbersinC strchr()functioninC StructureofaCprogram PowerFunctioninC MallocinC TablePrograminC TypesofRecursioninC ConvertUppercasetoLowercaseinC UnaryOperatorinC ArithmeticOperatorinC CeilFunctioninC RelationalOperatorinC AssignmentOperatorinC Pre-incrementandPost-incrementOperatorinC PointervsarrayinC RestrictkeywordinC Theexit()functioninC ConstQualifierinC SequencePointsinC AnagraminC IncrementandDecrementOperatorsinC LogicalANDOperatorinC ShiftOperatorsinC Near,Far,andHugepointersinClanguage MagicNumberinC RemoveDuplicateElementsfromanArrayinC GenericLinkedlistinC isalnum()functioninC isalpha()functioninC BisectionMethodinC snprintf()functioninC RemoveanelementfromanarrayinC SquareRootinC isprint()functioninC isdigit()functioninC isgraph()functioninC LogicalNOT(!)OperatorinC Self-referentialstructure BreakVs.ContinueinC Forvs.WhileloopinC MCQ ClanguageMCQ ClanguageMCQPart2 Math PrimeNumbersList CompositeNumbersList SquareNumbersList BinaryNumbersList FibonacciNumbersList OuncesinaCup OuncesinaPound OuncesinaGallon OuncesinaLiter OuncesinaPint OuncesinaQuart OuncesinaTablespoon CInterview CInterviewQuestions next→ ←prev CFunctionPointer Asweknowthatwecancreateapointerofanydatatypesuchasint,char,float,wecanalsocreateapointerpointingtoafunction.Thecodeofafunctionalwaysresidesinmemory,whichmeansthatthefunctionhassomeaddress.Wecangettheaddressofmemorybyusingthefunctionpointer. Let'sseeasimpleexample. #include intmain() { printf("Addressofmain()functionis%p",main); return0; } Theabovecodeprintstheaddressofmain()function. Output Intheaboveoutput,weobservethatthemain()functionhassomeaddress.Therefore,weconcludethateveryfunctionhassomeaddress. Declarationofafunctionpointer Tillnow,wehaveseenthatthefunctionshaveaddresses,sowecancreatepointersthatcancontaintheseaddresses,andhencecanpointthem. Syntaxoffunctionpointer returntype(*ptr_name)(type1,type2…); Forexample: int(*ip)(int); Intheabovedeclaration,*ipisapointerthatpointstoafunctionwhichreturnsanintvalueandacceptsanintegervalueasanargument. float(*fp)(float); Intheabovedeclaration,*fpisapointerthatpointstoafunctionthatreturnsafloatvalueandacceptsafloatvalueasanargument. Wecanobservethatthedeclarationofafunctionissimilartothedeclarationofafunctionpointerexceptthatthepointerisprecededbya'*'.So,intheabovedeclaration,fpisdeclaredasafunctionratherthanapointer. Tillnow,wehavelearnthowtodeclarethefunctionpointer.Ournextstepistoassigntheaddressofafunctiontothefunctionpointer. float(*fp)(int,int);//Declarationofafunctionpointer. floatfunc(int,int);//Declarationoffunction. fp=func;//Assigningaddressoffunctothefppointer. Intheabovedeclaration,'fp'pointercontainstheaddressofthe'func'function. Note:Declarationofafunctionisnecessarybeforeassigningtheaddressofafunctiontothefunctionpointer. Callingafunctionthroughafunctionpointer Wealreadyknowhowtocallafunctionintheusualway.Now,wewillseehowtocallafunctionusingafunctionpointer. Supposewedeclareafunctionasgivenbelow: floatfunc(int,int);//Declarationofafunction. Callinganabovefunctionusingausualwayisgivenbelow: result=func(a,b);//Callingafunctionusingusualways. Callingafunctionusingafunctionpointerisgivenbelow: result=(*fp)(a,b);//Callingafunctionusingfunctionpointer. Or result=fp(a,b);//Callingafunctionusingfunctionpointer,andindirectionoperatorcanberemoved. Theeffectofcallingafunctionbyitsnameorfunctionpointeristhesame.Ifweareusingthefunctionpointer,wecanomittheindirectionoperatoraswedidinthesecondcase.Still,weusetheindirectionoperatorasitmakesitcleartotheuserthatweareusingafunctionpointer. Let'sunderstandthefunctionpointerthroughanexample. #include intadd(int,int); intmain() { inta,b; int(*ip)(int,int); intresult; printf("Enterthevaluesofaandb:"); scanf("%d%d",&a,&b); ip=add; result=(*ip)(a,b); printf("Valueafteradditionis:%d",result); return0; } intadd(inta,intb) { intc=a+b; returnc; } Output Passingafunction'saddressasanargumenttootherfunction Wecanpassthefunction'saddressasanargumenttootherfunctionsinthesamewaywesendotherargumentstothefunction. Let'sunderstandthroughanexample. include voidfunc1(void(*ptr)()); voidfunc2(); intmain() { func1(func2); return0; } voidfunc1(void(*ptr)()) { printf("Function1iscalled"); (*ptr)(); } voidfunc2() { printf("\nFunction2iscalled"); } Intheabovecode,wehavecreatedtwofunctions,i.e.,func1()andfunc2().Thefunc1()functioncontainsthefunctionpointerasanargument.Inthemain()method,thefunc1()methodiscalledinwhichwepasstheaddressoffunc2.Whenfunc1()functioniscalled,'ptr'containstheaddressof'func2'.Insidethefunc1()function,wecallthefunc2()functionbydereferencingthepointer'ptr'asitcontainstheaddressoffunc2. Output ArrayofFunctionPointers Functionpointersareusedinthoseapplicationswherewedonotknowinadvancewhichfunctionwillbecalled.Inanarrayoffunctionpointers,arraytakestheaddressesofdifferentfunctions,andtheappropriatefunctionwillbecalledbasedontheindexnumber. Let'sunderstandthroughanexample. #include floatadd(float,int); floatsub(float,int); floatmul(float,int); floatdiv(float,int); intmain() { floatx;//variabledeclaration. inty; float(*fp[4])(float,int);//functionpointerdeclaration. fp[0]=add;//assigningaddressestotheelementsofanarrayofafunctionpointer. fp[1]=sub; fp[2]=mul; fp[3]=div; printf("Enterthevaluesofxandy:"); scanf("%f%d",&x,&y); floatr=(*fp[0])(x,y);//Callingadd()function. printf("\nSumoftwovaluesis:%f",r); r=(*fp[1])(x,y);//Callingsub()function. printf("\nDifferenceoftwovaluesis:%f",r); r=(*fp[2])(x,y);//Calliungsub()function. printf("\nMultiplicationoftwovaluesis:%f",r); r=(*fp[3])(x,y);//Callingdiv()function. printf("\nDivisionoftwovaluesis:%f",r); return0; } floatadd(floatx,inty) { floata=x+y; returna; } floatsub(floatx,inty) { floata=x-y; returna; } floatmul(floatx,inty) { floata=x*y; returna; } floatdiv(floatx,inty) { floata=x/y; returna; } Intheabovecode,wehavecreatedanarrayoffunctionpointersthatcontaintheaddressesoffourfunctions.Afterstoringtheaddressesoffunctionsinanarrayoffunctionpointers,wecallthefunctionsusingthefunctionpointer. Output NextTopicDynamicMemoryAllocation ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter



請為這篇文章評分?