Search code examples
cpointersswap

Two methods of swapping integers using pointers, which is better?[C]


i have encountered two methods of swapping two integer values and I’m confused about the difference.

Method1(temp is a pointer):

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

Method2(temp is not a pointer):

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

I don’t understand the difference between two methods, and is one method better than the other?


Solution

  • Perhaps it's easier to understand the first (wrong) function if we draw it out?

    When the function is called, it will be something like this:

    +---+      +-------------+
    | a | ---> | value for a |
    +---+      +-------------+
    
    +---+      +-------------+
    | b | ---> | value for b |
    +---+      +-------------+
    

    Then after the initialization of temp you will have this:

    +---+            +-------------+
    | a | -----+---> | value for a |
    +---+      |     +-------------+
               |
    +------+   |
    | temp | --/
    +------+
    
    +---+      +-------------+
    | b | ---> | value for b |
    +---+      +-------------+
    

    You have two pointers, pointing to the same location.

    Then you do the assignment

    *a = *b;
    

    which leads to this situation:

    +---+            +-------------+
    | a | -----+---> | value for b |
    +---+      |     +-------------+
               |
    +------+   |
    | temp | --/
    +------+
    
    +---+      +-------------+
    | b | ---> | value for b |
    +---+      +-------------+
    

    As can easily be seen, the value for a is lost.


    PS.

    Whenever you have troubles with pointers, and can't really visualize what's happening, I recommend you take a step back, fetch a pencil and paper, and draw it all out.