Challenge - 5 Problems
Reference vs Pointer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of reference and pointer modification
What is the output of this C++ code?
C++
#include <iostream> int main() { int x = 10; int &ref = x; int *ptr = &x; ref = 20; *ptr = 30; std::cout << x << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that both reference and pointer can modify the original variable.
✗ Incorrect
Both the reference and the pointer refer to the same variable x. First, ref = 20 changes x to 20, then *ptr = 30 changes x to 30. So the final output is 30.
❓ Predict Output
intermediate2:00remaining
Pointer vs reference reassignment
What is the output of this C++ code?
C++
#include <iostream> int main() { int a = 5, b = 10; int *ptr = &a; int &ref = a; ptr = &b; ref = b; std::cout << a << " " << b << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that references cannot be reseated but pointers can.
✗ Incorrect
The pointer ptr is changed to point to b, but the reference ref still refers to a. However, ref = b assigns the value of b to a, so a becomes 10. b remains 10. So output is '10 10'.
🔧 Debug
advanced2:00remaining
Identify the error in pointer and reference usage
Which option will cause a compilation error in this code snippet?
C++
int x = 5; int &ref = x; int *ptr = &x; // Options below show different assignments:
Attempts:
2 left
💡 Hint
Check if the types on both sides match for references.
✗ Incorrect
Option B tries to create a reference to an int pointer (int*), but declares it as int& which is a reference to int. This is a type mismatch causing a compilation error.
🧠 Conceptual
advanced2:00remaining
Difference in memory behavior of references and pointers
Which statement correctly describes the difference between references and pointers in C++?
Attempts:
2 left
💡 Hint
Think about whether you can change what a reference or pointer points to after creation.
✗ Incorrect
Pointers can be changed to point to different objects anytime. References must be initialized once and cannot be changed to refer to another object later.
❓ Predict Output
expert3:00remaining
Output of complex pointer and reference manipulation
What is the output of this C++ code?
C++
#include <iostream> void func(int *&ptrRef, int &ref) { *ptrRef = ref + 5; ref = *ptrRef + 5; ptrRef = &ref; } int main() { int a = 1, b = 2; int *p = &a; func(p, b); std::cout << a << " " << b << " " << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Track carefully how the pointer reference and reference parameters modify values and pointers.
✗ Incorrect
Initially, p points to a=1, b=2.
*ptrRef = ref + 5; sets *p = 2 + 5 = 7, so a=7.
ref = *ptrRef + 5; sets b = 7 + 5 = 12.
ptrRef = &ref; now p points to b.
In main, a=7, b=12, *p = b = 12.
Output: '7 12 12'.