Monday, 18 October 2010

34. Pointer and Functions

Passing addresses to Functions:

Look at this porgram

#include<stdio.h>
void arnob(int,int)
main( )
{
int a=10,b=20;
arnob(&a,&b);
printf("\na=%d",a);
printf("\nb=%d",b);
}

arnob(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

The output of the above program would be:
a=20
b=10

  When we send the address of  a and b it come in the function arnob. But we know that the normal variable can not store the address of a variable. So if we want to store the address of a and b we mast declere the pointer type variable. Because we know that only pointer type variable can store the address of a variable. So in the function arnob we declear two pointer x and y to store the address of a and b. And we also declear a normal variable t. Now we put the value of *x in t. Also we know that *x mean 'value at address x' that means  a. And we know a=10. So t=*x mean that t=a i mean t=10. Now *x=*y mean that a=b. So tha valu of a is now 20. *y=t, we know that the valu of t=10. So *y=t mean b=10. Look at this porgram we work in tha fanction arnob. But the value of a and b change in the main function.

post by Arnob

No comments:

Post a Comment