What is a Pointer variable?
A pointer variable is a special variable which holds the address (memory location) of another variable.
e.g
Code snippet :
int main(){
int x = 10 ; // normal variable
int *ptr = &x; // here ‘ptr‘ is pointer variable and initialised with ‘address of x‘
printf(”value of x is %d”, *ptr);
return 0;
}
output :
value of x is 10
Explantion
- ‘&‘ when used with variable name (here ‘x‘) represents the ‘address of that variable‘. Thus ‘ptr‘ stores the address of x .
- ‘*ptr‘ represents the value stored at the location hold by ‘ptr‘. This is known as ‘dereferencing a pointer variable’.
Now, What is Function Pointer ?
A Function pointer is a pointer variable that holds the ‘Address of a Function‘.
Note : In low level code generation every function call is replaced by the address of the function.
Function name itself represents the address of a Function.
Function Pointer Syntax :
1) Function Pointers are declared as
<return_type> (* <function_pointer_variable>)(<argument types>)
e.g
note : return type and argument types or number may change as per the requirement
int (*function_ptr) (int,int) =NULL;
- function_ptr is pointer to a function which takes two int arguments and returns an int.
- funcion_ptr can take the address of any function which takes two int arguments and returns an int.
- Assigning address of a function with a different prototype is “incompatible pointer assignment”.
2) Initialisation of Function Pointer
<function_pointer_variable> = <function_name>
or
<function_pointer_variable> = &<function_name>
e.g
Let the function pointer variable be function_ptr and the function name be ‘sum‘
then, as per initialisation rule :
function_ptr = sum;
or
function_ptr = ∑
3) Dereferencing of Function Pointer
<function_pointer_variable>(<arguments>)
or
(*<function_pointer_variable>)(<arguments>)
e.g
Let the function pointer variable be function_ptr
then, as per dereferencing rule :
note : arguments are of int types as per above declaration
function_ptr(12,23);
or
(*function_ptr)(12,23);
Example code given below for function pointer usage relates everything with above given pointer example.
e.g
Code snippet :
//function definition
int sum(int a, int b)
{
return a + b;
}
int main(){
//declaration as well as initialisation of function pointer
int (*function_ptr) (int,int) = sum ;
printf(”Sum of 10 and 20 is %d”, function_ptr(10,20));
return 0;
}
output :
Sum of 10 and 20 is 30
Explantion
- First we define the function ‘sum‘ and then we declare the ‘function pointer’ named ‘function_ptr‘ and initialises it with the ‘address of sum function‘ .
- Then we ‘deference the function pointer’ by invoking ‘function_ptr(10,20)‘ . It indirectly invokes ‘sum(10,20)‘.
Note : Signature (return type as well as argument types and number) of function pointer should match with the signature of the function whose address it is going to hold.
written by Anup
Recent Comments