Why does this not swap a and b?

Viewed 60

I'm very new to C and just starting to learn pointers. I'm very confused by this piece of code in lecture. I'm wondering if anyone can explain it to help me understand.

#include <stdio.h>
void swap(int *p1, int *p2) 
{      int *p;
       p = p1; p1 = p2; p2 = p;
}
void main() 
{      int a, b;
       int *pointer_1, *pointer_2;
       scanf("%d, %d", &a, &b);
       pointer_1 = &a; pointer_2 = &b;
       if (a < b) swap(pointer_1, pointer_2);
       printf("\n%d > %d\n", *pointer_1, *pointer_2);
}
 

The problem is why this doesn't swap a and b?

3 Answers

In your code

 p = p1; p1 = p2; p2 = p;

you're swapping the addresses (the change is local to the function scope). You need to swap the values (*p1, *p2) stored in those memory locations.

This function

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

actually swaps nothing. The pointers are passed to the function by value

if (a < b) swap(pointer_1, pointer_2);

That is the function deals with its own local variables p1 and p2 that were initialized by copies of values of the original pointers used as argument expressions. Within the function these local variables are indeed swapped but the original pointers used as argument expressions stay unchanged.

You need to swap objects of the type int passed to the function swap by reference that is through pointers to them. That is you need to change values of the variables a and b defined in main.

So the function should look the following way

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

Dereferencing the pointers you get a direct access to the pointed variables a and b and can exchange their values.

If you want to exchange values of the pointers pointer_1 and pointer_2 themselves then the function can look the following way

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

and the function will be called like

if (a < b) swap( &pointer_1, &pointer_2);

That is again the arguments must be passed by reference through pointers to them. In this case the values of the variables a and b will not be changed but values of the pointers will be changed.

Try yourself the both approaches and compare their results. Output in main the variables a and b and the values of the dereferenced pointers as for example

printf("a = %d, b = %d\n", a, b );
printf("*pointer_1 = %d, *pointer_2 = %d\n", *pointer_1, *pointer_2);
void swap(int *p1, int *p2) 
{      
    int *p;
    p = p1; p1 = p2; p2 = p;
}

Your function, swap, does not actually modify the values of p1 and p2 You can fix it by replacing p = p1; p1 = p2; p2 = p; with this

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

In this case, we modify the value of what the pointer is pointing to.

Related