Challenge: Swap with Pointers
Completed
Complete the function void swapPtr(int* a, int* b) so it swaps the two values its pointers point to. The starter reads two numbers, calls it and prints them.
Input
Two integers.
Output
The two integers swapped.
Example
Input
3 8
Output
8 3
Editor
C++
Hints
*a is the value a points to.
Save *a in a temp variable, then *a = *b, then *b = temp.
Solution explanation
The function receives addresses, so writing through *a and *b changes x and y in main.
Show solution
#include <iostream>
using namespace std;
void swapPtr(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y;
cin >> x >> y;
swapPtr(&x, &y);
cout << x << " " << y << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module