Pointer with function in C
We can use pointers with functions in following ways:
Function returning pointer
In C language, a function can even return a pointer like other data types.
The syntax for function returning a pointer is:
Data_type *fun_name(Arguments);
Program to demonstrate a function returning pointer |
#include<stdio.h> int *sum(int a,int b) { int c=a+b; return &c; } int main() { int *s; s=sum(10,14); printf(“\nSum=%d”,*s); return(0); } |
Output |
Sum=30 |
Description |
In the above program, the function sum() is returning pointer as int *sum(int a,int b).
This function has been called within main() by taking a pointer variable s as int *s and assigning function calling statement to variable s as s=sum(10,14); |
Pointer to function
Function also has an address in memory. This address is used when the function is called.
By storing this address in a function pointer, the function can also be called through this pointer.
Using function pointers, functions are passed as arguments to other functions.
Program to demonstrate the use of pointer to function. |
#include<stdio.h>
void fun(int val) fp= &fun; fp(10); return(0); |
Output |
Value=10 |
Description |
In the above program, the function fun(int val) is defined.
Function pointer has been declared as void (*fp)(int). This pointer looks similar to function definition i.e. void is the return type and int is within parenthesis specifying argument of int type. fp= &fun statement assigns the address of function fun in function ponter fp. fp(10) calls function fun with argument value 2. |