Pointer with function in C
We can use pointers with functions in following ways:
Passing function arguments by reference
In this case, the addresses of actual arguments are stored in formal arguments in function definition and any changes made to the formal arguments in the function body are reflected back to the calling function and actual arguments will get latest values of formal arguments.
|Program to demonstrate the use of call by reference|
void show(int *a,int *b)
In the above program, values of x and y in main() are passed as actual arguments to the function show().
Address of x is stored in a and address of y is stored in b. *a is incremented and *b is decremented by 1 inside the function.
Then program control is transferred back to the main() after the function calling statement.
On displaying values of x and y, it is seen that changes made to a and b have direct effect on the values of x and y in the main() function i.e. value of *a is transferred to x and value of *b is transferred to y.
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:
|Program to demonstrate a function returning pointer|
int *sum(int a,int b)
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
The function pointer is a powerful feature in C language.
In memory, a function has a physical location that can be assigned to a pointer. This address is the entry point of the function and it is the address used when the function is called.
Once a pointer points to a function, the function can be called through that pointer.
Function pointers also allow functions to be passed as arguments to other functions or function pointers is a pointer that point to the address of a function.
|Program to demonstrate the use of pointer to function.|
void func(int x)
In the above program, the function func(int x) is defined.
Within main() a function pointer has been declared as void (*f)(int). The look of this pointer is similar to function definition i.e. void is the return type and int is within parenthesis specifying one argument of int type.
f= &func statement assigns the address of function func in function ponter f.
f(2) calls function func with actual argument value 2.
Best Books of C