0
Swap with pointers. Is it right way to use pointers in order to swap two numbers or is there any simpler method?
#include <iostream> using namespace std; void swap(int *c, int *d) { int *e, m; e = &m; m = *c; *c = *d; *d = *e; } int main() { int a, b; cout << "Program to swap two numbers using pointers\n" << endl; cout << "Please, input 1st number: "; cin >> a; cout << "Please, input 2nd number: "; cin >> b; swap(a, b); if (a != b) { cout << "\nThe 1st swapped number: " << a << endl; cout << "The 2nd swapped number: " << b << endl; } else cout << "Numbers are equal to each other! Please, input different numbers!" << endl; system("pause"); return 0; }
2 Antworten
+ 1
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x = *y;
*y = z;
}
int main()
{
int a, b;
cout<<"a= ";
cin>>a;
cout<<"\nb= ";
cin>>b;
swap(&a, &b);
cout << "\nAfter Swap\n";
cout << "a = " << a << " b = " << b << "\n";
return 0;
}
There is best way
0
Pointers aren't absolutely necessary for this. You don't even need references, but it would save memory to use references.
void swap(int& a, int &b) {
int tmp = a;
a = b;
b = tmp;
}