Search code examples
cpointerspass-by-referenceswapfunction-definition

Why does this not swap a and b?


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?


Solution

  • 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.