Pointers give greatly possibilities to 'C' functions which we are limited to return one value. With pointer parameters, our functions now ...
Skiptocontent
Pointersgivegreatlypossibilitiesto‘C’functionswhichwearelimitedtoreturnonevalue.Withpointerparameters,ourfunctionsnowcanprocessactualdataratherthanacopyofdata.
Inordertomodifytheactualvaluesofvariables,thecallingstatementpassesaddressestopointerparametersinafunction.
Inthistutorial,youwilllearn-
FunctionsPointersExample
FunctionswithArrayParameters
FunctionsthatReturnanArray
FunctionPointers
ArrayofFunctionPointers
FunctionsUsingvoidPointers
FunctionPointersasArguments
FunctionsPointersExample
Forexample,thenextprogramswapstwovaluesoftwo:
voidswap(int*a,int*b);
intmain(){
intm=25;
intn=100;
printf("mis%d,nis%d\n",m,n);
swap(&m,&n);
printf("mis%d,nis%d\n",m,n);
return0;}
voidswap(int*a,int*b){
inttemp;
temp=*a;
*a=*b;
*b=temp;}
}
Output:
mis25,nis100
mis100,nis25
Theprogramswapstheactualvariablesvaluesbecausethefunctionaccessesthembyaddressusingpointers.Herewewilldiscusstheprogramprocess:
Wedeclarethefunctionresponsibleforswappingthetwovariablevalues,whichtakestwointegerpointersasparametersandreturnsanyvaluewhenitiscalled.
Inthemainfunction,wedeclareandinitializetwointegervariables(‘m’and‘n’)thenweprinttheirvaluesrespectively.
Wecalltheswap()functionbypassingtheaddressofthetwovariablesasargumentsusingtheampersandsymbol.Afterthat,weprintthenewswappedvaluesofvariables.
Herewedefinetheswap()functioncontentwhichtakestwointegervariableaddressesasparametersanddeclareatemporaryintegervariableusedasathirdstorageboxtosaveoneofthevaluevariableswhichwillbeputtothesecondvariable.
Savethecontentofthefirstvariablepointedby‘a’inthetemporaryvariable.
Storethesecondvariablepointedbybinthefirstvariablepointedbya.
Updatethesecondvariable(pointedbyb)bythevalueofthefirstvariablesavedinthetemporaryvariable.
FunctionswithArrayParameters
InC,wecannotpassanarraybyvaluetoafunction.Whereas,anarraynameisapointer(address),sowejustpassanarraynametoafunctionwhichmeanstopassapointertothearray.
Forexample,weconsiderthefollowingprogram:
intadd_array(int*a,intnum_elements);
intmain(){
intTab[5]={100,220,37,16,98};
printf("Totalsummationis%d\n",add_array(Tab,5));
return0;}
intadd_array(int*p,intsize){
inttotal=0;
intk;
for(k=0;k
int*build_array();
intmain(){
int*a;
a=build_array();/*getfirst5evennumbers*/
for(k=0;k<5;k++)
printf("%d\n",a[k]);
return0;}
int*build_array(){
staticintTab[5]={1,2,3,4,5};
return(Tab);}
Output:
1
2
3
4
5
Andhere,wewilldiscusstheprogramdetails
Wedefineanddeclareafunctionwhichreturnsanarrayaddresscontaininganintegervalueanddidn’ttakeanyarguments.
Wedeclareanintegerpointerwhichreceivesthecompletearraybuiltafterthefunctioniscalledandweprintitscontentsbyiteratingtheentirefiveelementarray.
Noticethatapointer,notanarray,isdefinedtostorethearrayaddressreturnedbythefunction.Alsonoticethatwhenalocalvariableisbeingreturnedfromafunction,wehavetodeclareitasstaticinthefunction.
FunctionPointers
Asweknowbydefinitionthatpointerspointtoanaddressinanymemorylocation,theycanalsopointtoatthebeginningofexecutablecodeasfunctionsinmemory.
Apointertofunctionisdeclaredwiththe*,thegeneralstatementofitsdeclarationis:
return_type(*function_name)(arguments)
Youhavetorememberthattheparenthesesaround(*function_name)areimportantbecausewithoutthem,thecompilerwillthinkthefunction_nameisreturningapointerofreturn_type.
Afterdefiningthefunctionpointer,wehavetoassignittoafunction.Forexample,thenextprogramdeclaresanordinaryfunction,definesafunctionpointer,assignsthefunctionpointertotheordinaryfunctionandafterthatcallsthefunctionthroughthepointer:
#include
voidHi_function(inttimes);/*function*/
intmain(){
void(*function_ptr)(int);/*functionpointerDeclaration*/
function_ptr=Hi_function;/*pointerassignment*/
function_ptr(3);/*functioncall*/
return0;}
voidHi_function(inttimes){
intk;
for(k=0;k
intsum(intnum1,intnum2);
intsub(intnum1,intnum2);
intmult(intnum1,intnum2);
intdiv(intnum1,intnum2);
intmain()
{intx,y,choice,result;
int(*ope[4])(int,int);
ope[0]=sum;
ope[1]=sub;
ope[2]=mult;
ope[3]=div;
printf("Entertwointegernumbers:");
scanf("%d%d",&x,&y);
printf("Enter0tosum,1tosubtract,2tomultiply,or3todivide:");
scanf("%d",&choice);
result=ope[choice](x,y);
printf("%d",result);
return0;}
intsum(intx,inty){return(x+y);}
intsub(intx,inty){return(x-y);}
intmult(intx,inty){return(x*y);}
intdiv(intx,inty){if(y!=0)return(x/y);elsereturn0;}
Entertwointegernumbers:1348
Enter0tosum,1tosubtract,2tomultiply,or3todivide:2
624
Here,wediscusstheprogramdetails:
Wedeclareanddefinefourfunctionswhichtaketwointegerargumentsandreturnanintegervalue.Thesefunctionsadd,subtract,multiplyanddividethetwoargumentsregardingwhichfunctionisbeingcalledbytheuser.
Wedeclare4integerstohandleoperands,operationtype,andresultrespectively.Also,wedeclareanarrayoffourfunctionpointer.Eachfunctionpointerofarrayelementtakestwointegersparametersandreturnsanintegervalue.
Weassignandinitializeeacharrayelementwiththefunctionalreadydeclared.Forexample,thethirdelementwhichisthethirdfunctionpointerwillpointtomultiplicationoperationfunction.
Weseekoperandsandtypeofoperationfromtheusertypedwiththekeyboard.
Wecalledtheappropriatearrayelement(Functionpointer)witharguments,andwestoretheresultgeneratedbytheappropriatefunction.
Theinstructionint(*ope[4])(int,int);definesthearrayoffunctionpointers.Eacharrayelementmusthavethesameparametersandreturntype.
Thestatementresult=ope[choice](x,y);runstheappropriatefunctionaccordingtothechoicemadebytheuserThetwoenteredintegersaretheargumentspassedtothefunction.
FunctionsUsingvoidPointers
Voidpointersareusedduringfunctiondeclarations.Weuseavoid*returntypepermitstoreturnanytype.Ifweassumethatourparametersdonotchangewhenpassingtoafunction,wedeclareitasconst.
Forexample:
void*cube(constvoid*);
Considerthefollowingprogram:
#include
void*cube(constvoid*num);
intmain(){
intx,cube_int;
x=4;
cube_int=cube(&x);
printf("%dcubedis%d\n",x,cube_int);
return0;}
void*cube(constvoid*num){
intresult;
result=(*(int*)num)*(*(int*)num)*(*(int*)num);
returnresult;}
Result:
4cubedis64
Here,wewilldiscusstheprogramdetails:
Wedefineanddeclareafunctionthatreturnsanintegervalueandtakesanaddressofunchangeablevariablewithoutaspecificdatatype.Wecalculatethecubevalueofthecontentvariable(x)pointedbythenumpointer,andasitisavoidpointer,wehavetotypecastittoanintegerdatatypeusingaspecificnotation(*datatype)pointer,andwereturnthecubevalue.
Wedeclaretheoperandandtheresultvariable.Also,weinitializeouroperandwithvalue“4.”
Wecallthecubefunctionbypassingtheoperandaddress,andwehandlethereturningvalueintheresultvariable
FunctionPointersasArguments
Anotherwaytoexploitafunctionpointerbypassingitasanargumenttoanotherfunctionsometimescalled“callbackfunction”becausethereceivingfunction“callsitback.”
Inthestdlib.hheaderfile,theQuicksort“qsort()”functionusesthistechniquewhichisanalgorithmdedicatedtosortanarray.
voidqsort(void*base,size_tnum,size_twidth,int(*compare)(constvoid*,constvoid*))
void*base:voidpointertothearray.
size_tnum:Thearrayelementnumber.
size_twidthTheelementsize.
int(*compare(constvoid*,constvoid*):functionpointercomposedoftwoargumentsandreturns0whentheargumentshavethesamevalue,<0whenarg1comesbeforearg2,and>0whenarg1comesafterarg2.
Thefollowingprogramsortsanintegersarrayfromsmalltobignumberusingqsort()function:
#include
#include
intcompare(constvoid*,constvoid*);
intmain(){
intarr[5]={52,14,50,48,13};
intnum,width,i;
num=sizeof(arr)/sizeof(arr[0]);
width=sizeof(arr[0]);
qsort((void*)arr,num,width,compare);
for(i=0;i<5;i++)
printf("%d",arr[i]);
return0;}
intcompare(constvoid*elem1,constvoid*elem2){
if((*(int*)elem1)==(*(int*)elem2))return0;
elseif((*(int*)elem1)0whenarg1comesafterarg2.Theparametersareavoidpointerstypecastedtotheappropriatearraydatatype(integer)
WedefineandinitializeanintegerarrayThearraysizeisstoredinthenumvariableandthesizeofeacharrayelementisstoredinwidthvariableusingsizeof()predefinedCoperator.
Wecalltheqsortfunctionandpassthearrayname,size,width,andcomparisonfunctiondefinedpreviouslybytheuserinordertosortourarrayinascendingorder.Thecomparisonwillbeperformedbytakingineachiterationtwoarrayelementsuntiltheentirearraywillbesorted.
Weprintthearrayelementstobesurethatourarrayiswellsortedbyiteratingtheentirearrayusingforloop.
YouMightLike:
CTutorialforBeginners:LearnCProgrammingLanguageBasics
CConditionalStatement:IF,IFElseandNestedIFElsewithExample
LoopsinC:For,While,DoWhileloopingStatements[Examples]
Differencebetweenstrlen()andsizeof()forstringinC
20+BestCIDEforWindows,Mac&Linux(2022Editors)
Postnavigation
ReportaBug
Previous
PrevNextContinue
Scrolltotop
ToggleMenuClose
Searchfor:
Search