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 manipulation
What is the output of this C++ code that uses pointers to change a variable's value?
C++
#include <iostream> int main() { int x = 10; int* p = &x; *p = 20; std::cout << x << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that *p accesses the value pointed to by p.
✗ Incorrect
The pointer p holds the address of x. Using *p = 20 changes the value of x to 20. So printing x outputs 20.
🧠 Conceptual
intermediate1:30remaining
Why use pointers for function arguments?
Why do we use pointers as function arguments in C++?
Attempts:
2 left
💡 Hint
Think about what happens when you want a function to change a variable outside its own scope.
✗ Incorrect
Passing a pointer lets the function access and change the original variable's value, not just a copy.
❓ Predict Output
advanced2:00remaining
Output of pointer arithmetic
What is the output of this C++ code that uses pointer arithmetic on an array?
C++
#include <iostream> int main() { int arr[] = {5, 10, 15}; int* p = arr; std::cout << *(p + 1) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Pointer arithmetic moves the pointer to the next element in the array.
✗ Incorrect
p points to arr[0]. Adding 1 moves it to arr[1], which is 10.
🔧 Debug
advanced2:00remaining
Identify the pointer error
What error will this C++ code produce?
C++
#include <iostream> int main() { int* p; *p = 10; std::cout << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Think about what happens if you dereference a pointer that does not point to valid memory.
✗ Incorrect
The pointer p is uninitialized and points to an unknown location. Dereferencing it causes a runtime crash (segmentation fault).
🚀 Application
expert3:00remaining
Using pointers to swap two variables
Which option correctly swaps the values of two integers using pointers in C++?
C++
void swap(int* a, int* b) { // Fill in } int main() { int x = 3, y = 7; swap(&x, &y); std::cout << x << " " << y << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember to use * to access the values the pointers point to, and swap them using a temporary variable.
✗ Incorrect
Option A correctly uses a temporary variable to swap the values pointed to by a and b. Other options either swap pointers or overwrite values incorrectly.