Sunday 3 February 2013


Pointers to Functions in C:
Applications of Pointers to Functions:
#include <stdio.h>
int add(int a, int b){
return a b;
}
int main(){
int c;
int (*ptr)(int, int); 
ptr=add;
c=ptr(2, 8);
printf("%d", c);
return 0;
}

1: Refer Multiple Functions through theSame Function Pointer:

#include <stdio.h>
void f1(){
printf("In f1().\n");
}
void f2(){
printf("In f2().\n");
}
int main(){
void (*ptr)(); 
ptr=f1;
ptr(); 
ptr=f2;
ptr(); 
return 0;
}

2. Pass Functions as Arguments to OtherFunctions:

#include <stdio.h>
void f1(){
printf("In f1().\n");}
void f2(){
printf("In f2().\n");
}
void msg(int nCnt, void (*ptr)()){
int i;
for(i=0; i<nCnt; i )
ptr();
}
int main(){
msg(3, f1);
msg(2, f2); 
return 0;
}

Note: Many of the standard C library functionsrequire functions to be passed as arguments.e.g. “qsort( )” function sorts the data usingQuick Sort algorithm.
void qsort(void *base, size_t nelem, size_twidth, int (*fcmp)(const void *, const void *));

It accepts a comparator function to be passedas an argument. It declares its type as:
int sort_function( const void *a, const void *b);

3: Array of Functions:


#include <stdio.h>
void f1() { printf("In f1().\n"); }
void f2() { printf("In f2().\n"); }
void f3() { printf("In f3().\n"); }
void f4() { printf("In f4().\n"); }
void f5() { printf("In f5().\n"); }
int main(){
int i; 
void (*ptrArr[])() = { f1, f2, f3, f4, f5 }; 
for(i=0; i<5; i )
ptrArr[i](); 
return 0;
}

Idiosyncrasies Involved in the Usage of Pointers to Functions:

#include <stdio.h>
void f() { 
printf("In f().\n"); 
}
int main(){
void (*ptr)();
ptr=f; 
ptr(); 
(ptr)(); 
(*ptr)();
(**ptr)(); 
(***ptr)(); 
(****ptr)(); 
(*****ptr)(); 
return 0;
}

No comments:

Post a Comment