Preview
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 |
#include<stdio.h> void show(int *a,int *b) { (*a)++; (*b)–; printf(“\n%d,%d”,*a,*b); } int main() { int x=10,y=8; printf(“\n%d,%d”,x,y); show(&x,&y); printf(“\n%d,%d”,x,y); return(0); } |
Output |
10,8 11,7 11,7 |
Description |
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:
Data_type *fun_name(Arguments);
Program |
#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); |
Best Sellers