Passing pointer to a function (or)
pointer and functions
Case1: pointers
are often passed to a function as arguments call be reference mechanism.
/* EXAMPLE PROGRAM FOR CALL BY ADDRESS (or)
CALL BY REFERENCE */
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
main()
{
int
x,y;
clrscr();
printf(“\n
Enter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore
swapping the values are: ");
printf("\nx
:%d, y :%d",x,y);
swap(&x,&y);
printf("\n After
swapping the values are: ");
printf("\n x
:%d, y:%d",x,y);
}
void
swap(int *p, int *q)
{
int
temp;
temp=*p;
*p=*q;
*q=temp;
}
Case2: ‘C’ allows a pointer
can store the address of a function.
Syn: returntype(*pv)( );
We
can call the function by using pointer variable.
Example program:
#include<stdio.h>
#include<conio.h>
int show(void);
main()
{
Int (*p)();
P=show;
(*p)();
Printf(“%u”,show);
}
int
show()
{
printf(“address of show
is: “);
}
Case 3: pointers
can be passed as an argument from one function to another function. (or) ‘C’
allows a pointer to pass one function to another function as an argument.
Syntax: returntype
function_name (pointer to function
(other arguments));
Example
program:
int
add(int,int);
int
process(int (*) (int,int));
main()
{
int x;
clrscr();
x=process(add);
printf(“sum of numbers %d”,x);
}
int
process(int (*p) (int a,int b))
{
int c,a=20,b=10;
c=(*p)(a,b);
return c;
}
int
add(int a, int b)
{
return a+b;
}
No comments:
Post a Comment