Question

#include <stdio.h>
#include <string.h>

void swap(int *p1, int *p2) 
{
  int *temp;
temp=p1;
p1=p2;
p2=temp;
}

main()
{
int n1=10,n2=20;
printf("%d,%d\n",n1++,++n2);
swap(&n1,&n2);
printf("%d,%d",++n1,n2++);
}

When I run this code output is 10,21 and 12,21. My question is why values of N1 and N2 are not swapped? Since function swap uses pointers and method is called by reference shouldn't they swap? Or am I missing some concept? Thanks in advance

Was it helpful?

Solution

You've swapped the pointers rather than the values. Remember that C exclusively uses pass-by-value, and so these pointers were passed by value. To swap the things that they refer to you need to de-reference the pointers.

void swap(int *p1, int *p2) 
{
    int temp;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
}

One way to thing about this is that you need to be assigning values of type int. But your code assigns values of type int*. And so purely on that analysis which is based only on types, you are able to reject your code.

OTHER TIPS

void swap(int *p1, int *p2) 
{
    int temp;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
}

The pointers you are swapping in your swap() function are local variables of this function. So this swapping has no effect outside this function.

To correctly swap values use the code that Wojtek posted.

You might also want to have have a look at this question: What is the fastest way to swap values in C?

The answer makes use of an XOR swapping algorithm.

change your swap function as follow

void swap(int *p1, int *p2) 

    {
      int temp;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
    }

Note: you are try to make assignment on addresses of variables at your swap function

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top