2. Pointers point to the address of a function
A running program is allocated a certain space in the main memory
The executable compiled program code and the used variables
are both put inside this memory
Thus a function in the program code has an address.
Can be declared, assigned values, and then used to access the functions
they point to
7. Must be initialized prior to use
Assign the address of a function to a function pointer
Simply uses the name of a function
Optional to use the address operator & in front of the
function’s name
8. Must be initialized prior to use
int add(int,int);
fpointer = add;
Names of these functions, add - pointers
to those functions
9.
10. Two ways
Use the name of the function pointer instead of the
name of the function
Explicitly dereference it
result1 = fpointer(4, 5);
Function cannot be
passed as parameter to
another function
11. #include <stdio.h>
/*Define a pointer to a function */
int(*fpointer)(int, int);
int add(int a, int b){return(a + b);}
int sub(int a, int b) {return(a - b);}
int main(){
fpointer = &add;
printf("%d n", fpointer(4, 5));
fpointer = sub; // Function’s name can also be used to get functions’address
printf(“%d n”, (*fpointer)(6, 2));
return 0;
}
12.
13. #include <stdio.h>
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int arith(int f(int,int))
{
int x=5, y=4,s;
s=(*f)(x,y)
return s;
}
int main()
{
printf("n Add: %d",arith(add));
printf("n Sub: %d",arith(sub));
return 0;
}
14. #include <stdio.h>
int even(int a)
{
if(a%2==0)
return a;
else
return 0;
}
int odd(int a)
{
if(a%2!=0)
return a;
else
return 0;
}
int sum(int f(int), int m, int n)
{
int s = 0;
for(int i=m; i<=n;++i)
s+=f(i); or s+=(*f)(i);
return s;
}
int main()
{
printf("n Sum of Even numbers: %d",sum(even,5,10));
printf("n Sum of Odd numbers: %d",sum(odd,5,10));
return 0;
}
15.
16. #include <stdio.h>
int add(int x,int y)
{
return x + y;
}
int sub(int x,int y)
{
return x - y;
}
int (*getOperator(const char oper))(int, int)
{
if(oper == '+') return &add;
if(oper == '-') return ⊂
}
int main()
{
int x = 20,y = 10,z = 0;
int (*func)(int, int);
func = getOperator('+');
z = func(x,y);
printf("Add : %dn",z);
func = getOperator('-');
z = func(x,y);
printf("Sub : %dn",z);
return 0;
}
17. #include <stdio.h>
#include <stdlib.h>
typedef int(*pfOperator)(int, int);
int add(int x,int y)
{
return x + y;
}
int sub(int x,int y)
{
return x - y;
}
pfOperator getOperator(const char oper)
{
if(oper == '+') return &add;
if(oper == '-') return ⊂
}
int main()
{
int x = 20,y = 10,z = 0;
pfOperator func = NULL;
func = getOperator('+');
z = func(x,y);
printf("Add : %dn",z);
func = getOperator('-');
z = func(x,y);
printf("Sub : %dn",z);
return 0;
}
18.
19. #include <stdio.h>
int(*fpointer[2])(int, int);
int add(int a, int b){return(a + b);}
int sub(int a, int b) {return(a - b);}
int main(){
fpointer[0] = &add;
printf("%d n", (*fpointer[0])(4, 5));
fpointer[1] = sub;
printf(“%d n”, fpointer[1](6, 2));
return 0;}