Challenge - 5 Problems
Pointer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of pointer arithmetic
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { int arr[3] = {10, 20, 30}; int* p = arr; std::cout << *(p + 1) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Pointer arithmetic moves the pointer by the size of the pointed type.
✗ Incorrect
The pointer p points to arr[0]. Adding 1 moves it to arr[1], which is 20.
❓ Predict Output
intermediate2:00remaining
Dereferencing a null pointer
What happens when this C++ code runs?
C++
#include <iostream> int main() { int* p = nullptr; std::cout << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Dereferencing a null pointer is unsafe.
✗ Incorrect
Dereferencing nullptr causes undefined behavior, usually a crash (segmentation fault).
❓ Predict Output
advanced2:00remaining
Dangling pointer after delete
What is the output of this code?
C++
#include <iostream> int main() { int* p = new int(42); delete p; std::cout << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Accessing memory after delete is unsafe.
✗ Incorrect
After delete, pointer p is dangling. Dereferencing it causes undefined behavior.
❓ Predict Output
advanced2:00remaining
Pointer type mismatch
What error or output does this code produce?
C++
#include <iostream> int main() { int x = 5; double* p = (double*)&x; std::cout << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Casting pointer types incorrectly can cause problems.
✗ Incorrect
Casting int* to double* and dereferencing causes undefined behavior because the memory layout differs.
🧠 Conceptual
expert2:00remaining
Common cause of memory leak with pointers
Which option best describes a common cause of memory leaks when using pointers in C++?
Attempts:
2 left
💡 Hint
Memory leaks happen when allocated memory is not freed.
✗ Incorrect
If you allocate memory with new but never call delete, the memory stays allocated and leaks.