Help me swap values using pointers

So i'm reading my c++ book and it describes how to swap two values using pointers, it gives an example

int temp = *p1;
*p1 = *p2;
*p2 = temp;

I just have trouble wrapping my head around this and how exactly it works.

If I pass two variables like a and b, does the first variable go to *p1 and the second go to *p2 ?

When it says "temp = *p1" is that changing the value of temp or *p1 ?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void MySwap( int *p1, int *p2 )
{
  int temp = *p1;  // Store value stored in location p1 is pointing to into temp
  *p1 = *p2;       // Store value stored in location p2 is pointing to into location p1 is pointing to
  *p2 = temp;      // Store value of temp in location p2 is pointing to
}

int main( int argc, char* argv[] )
{
  int a = 1, b = 2;
  std::cout << "a is " << a << ", b is " << b << std::endl;
  MySwap( &a, &b );
  std::cout << "a is " << a << ", b is " << b << std::endl;
}
Last edited on
Ok thank you that it explains it.
Topic archived. No new replies allowed.