can anyone explain me why the values are not swapped in the below code ??

main()
{
int *i,*j;
*i=4000;
*j=9000;
f(i,j);
printf(" %d %d",*i,*j); //output =4000 9000
}

void f( int *a, int *b)
{
int *temp;
temp=a;
a=b;
b=temp;
}

Recommended Answers

All 5 Replies

Because you're just swapping addresses, not values. You want to dereference the pointers:

void f( int *a, int *b)
{
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}

i got your answer to how swap pointers ...
But can u tell me what's happening in the code i have written ???
is the address which is passed by i & j is copied in pointers a & b and only adress among a & b is swapped ... so no effect on i & j ..is this what happening ???
can u explain me details what actually happening in my code ...

> can anyone explain me why the values are not swapped in the below code ??
Another problem is that your pointers are uninitialised - who knows, maybe they both point at the same memory location.

> can anyone explain me why the values are not swapped in the below code ??
Another problem is that your pointers are uninitialised - who knows, maybe they both point at the same memory location.

i have work with the same code after initializing it ..but there is no change in output ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.