Pointer to function in c
Like the pointer to normal variables, we can also use pointers to point the functions.
In this tutorial, we will learn how to use function pointer with an example.
Is each function has unique memory address?
Yes. Like every variables function also has unique memory address.
Example
/* * Program : Printing function's memory address * Language : C */ #include<stdio.h> void hello() { printf("Hello\n"); } int main() { //function name itself holds the memory address of a function printf("Address of function hello = %p\n",hello); return 0; }
Function pointer syntax
void (*fptr)();
We must enclose the function pointer variable with (). like (*fptr).
Where *fptr is a function pointer, capable of referring a function whose return type is void and also it will not take any argument ().
Similarly, if we want to point a function whose return type is int and it takes one integer argument i.e. int fun(int); then the declaration will be,
int (*fptr)(int);
Referencing and Dereferencing of Function Pointer
Referencing
1. Declare correct function pointer.
2. Assign function address to that pointer.
Example
#include<stdio.h> void hello() { printf("Hello\n"); } int main() { void (*fptr)(); fptr = hello; //fptr references function hello return 0; }
Dereferencing
1. Calling the actual function using the function pointer.
Using value at operator *, we can call the function. i.e. (*fptr)();
Example
#include<stdio.h> void hello() { printf("Hello\n"); } int main() { void (*fptr)(); fptr = hello; //fptr references function hello (*fptr)(); //dereferencing function pointer return 0; }
Function Pointer with Arguments
Example
/* * Program : Function Pointer with argument * Language : C */ #include<stdio.h> int sum(int x, int y) { return x+y; } int main() { int ans; int (*fptr)(int,int); fptr = sum; ans = (*fptr)(10,5); printf("10+5 = %d\n",ans); ans = (*fptr)(100,10); printf("100+10 = %d\n",ans); return 0; }