Skip to main content

Function Pointer In C

Function Pointers in C

Function Pointer that refers to the address of other function. 
We will passed variable, constants, structure variables to a function as argument. But have you ever tried or thought to pass a function as an argument to another function. If not, then let us do it together. At first sight it may appear a bit confusing to you but trust me it is as simple as writing “int main()”.

It is used to pass the function address to the another function or create the array of function or create function inside the structure  or create call back function used in layered software like AUTOSAR.

Function_pointer_in_C













 

 

 

 

 

 

 

 

 

 

 

 

 

 

Syntax :

return_type(*pointer_name)(function_argument)

example :
void (*foo) (void);



now foo can point to any function it should have return type of void and argument type is void.


int add(int a , int b)
{

return a+b;
}

now i want to create variable should point to add function

int (*foo)(int ,int);

Assign an address to a function Pointer:

foo = add;   //short way
or 
foo = &add 

 Calling the Function using Function Pointer:

 result = add(10,20);  //short way
or
result = (*foo)(10,20);


both will work


How to pass function pointer as a argument:

 void pass_pointer_function ( void)
{
 int Result;
 
 Result = PassPointer(&add); 

}

 


int PassPointer(int (*passptr)(int ,int))
{
ans = (*passptr)(10,20);
//or  
ans = passptr(10,20);
 return ans;
}



How to use array of function pointer :



typedef int (*foo)(int ,int);

foo arry_off_func[0] = {NULL};      //one way
or
int (*foo[10])(int,int) ={null};  //other way







Comments

Popular posts from this blog

CAN INTERVIEW QUESTIONS

Qualifiers and Modifier in C

RTOS Real time operating system interview questions

CAN INTERVIEW QUESTIONS 2

What is UDS protocol

Memory mapping in c

TOP IOT PLATFORMS