I am studying pointers and I encountered this program:
#include <stdio.h>
void swap(int *,int *);
int main()
{
int a=10;
int b=20;
swap(&a,&b);
printf("the value is %d and %d",a,b);
return 0;
}
void swap(int *a,int*b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf("%d and%d\n",*a,*b);
}
Can any one tell me why this main function return the value reversed? The thing I understood till now is that the function call in C does not affect the main function and it’s values.
I also want to know how much the space a pointer variable occupied like integer have occupied the 2 bytes and the various application use and advantages of the pointer…
You are correct: a function in C cannot directly affect the values in the caller. But the values that are being given to
swap()are not the values ofaandb. Rather, they are pointers to those values–basically, the address in memory whereaandblive. Sinceswaphas those addresses, it can then write to those memory locations and effectively changeaandb.Good luck with pointers, by the way. It’s the hardest thing about C to get if you’re coming from a context that doesn’t have them. I came to C by way of Perl, and I broke my brain on pointers several times. But it’ll open up a whole new world once you understand them.