Here is an example of function pointers and how different pointers remain same in size can be understood through the following code
Just a simple mathematical problem.....of perform the basic functions using function pointers, and also passing functions in void* as a parameter....
#include <stdio.h>
int add(int a,int b);
int sub(int a, void * b);
int mul(int a,int b);
int div(int a,int b);
int operation(int a,int b,int (*function)(int,int));
int main (int argc, const char * argv[])
{
//Every of this address is of 8 bytes
printf("%lu\n",sizeof(int *));
printf("%lu\n",sizeof(float *));
printf("%lu\n",sizeof(void *));
printf("%lu\n",sizeof(&add));
int (*addptr)(int,int);//create a function pointer for add
addptr = &add; //though & is not necessary since its points to the address
printf("%lu\n",sizeof(addptr));
printf("addittion%d\n",(addptr)(2,3));
int (*subptr)(int,void *);//create a function pointer for sub
subptr =⊂
printf("subtract%d\n",(subptr)(5,(void *)3));//Pass an object of anytype
printf("mutliply->%d\n",operation(2,3,mul));//passing the base address of the method to call
printf("division->%d\n",operation(6,2,div));
return 0;
}
int operation (int a, int b, int (*functocall)(int,int))
{
return (*functocall)(a,b);
}
int div(int a,int b)
{
return (a/b);
}
int mul(int a,int b)
{
return (a*b);
}
int add(int a,int b)
{
return (a+b);
}
int sub(int a,void *b)//resultant is void so can send data of any type
{
return (a-(int)b);
}
0 comments:
Post a Comment