answersLogoWhite

0

There is no benefit in swapping two numbers using a pointer. It's actually quicker to swap the two numbers themselves. However the following shows how to swap values by changing the pointers to those value.

#include <iostream>

int main()

{

int X = 5;

int Y = 6;

// Point to the values in X and Y.

int *pX = &X;

int *pY = &Y;

// Print current values and the values being pointed at:

std::cout << "Before swapping:" << std::endl;

std::cout << " X = " << X << ", Y = " << Y << std::endl;

std::cout << "pX = " << *pX << ", pY = " << *pY << std::endl;

// Swap the pointers.

pX = &Y;

pY = &X;

// Print current values and the values being pointed at:

std::cout << "After swapping:" << std::endl;

std::cout << " X = " << X << ", Y = " << Y << std::endl;

std::cout << "pX = " << *pX << ", pY = " << *pY << std::endl;

return( 0 );

}

User Avatar

Wiki User

13y ago

What else can I help you with?