0
0
C++programming~20 mins

Why pointers are needed in C++ - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Pointer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
A10
B20
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Remember that *p accesses the value pointed to by p.
🧠 Conceptual
intermediate
1:30remaining
Why use pointers for function arguments?
Why do we use pointers as function arguments in C++?
ATo allow the function to modify the original variable's value
BTo make the function run faster by avoiding copying variables
CTo prevent the function from accessing the variable
DTo make the variable constant inside the function
Attempts:
2 left
💡 Hint
Think about what happens when you want a function to change a variable outside its own scope.
Predict Output
advanced
2: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;
}
A5
BCompilation error
C10
D15
Attempts:
2 left
💡 Hint
Pointer arithmetic moves the pointer to the next element in the array.
🔧 Debug
advanced
2: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;
}
ACompilation error: uninitialized pointer
BNo error, outputs garbage value
COutput: 10
DRuntime error: segmentation fault
Attempts:
2 left
💡 Hint
Think about what happens if you dereference a pointer that does not point to valid memory.
🚀 Application
expert
3: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;
}
Aint temp = *a; *a = *b; *b = temp;
Bint temp = a; a = b; b = temp;
C*a = *b; *b = *a;
Dint temp = *a; *b = *a; *a = temp;
Attempts:
2 left
💡 Hint
Remember to use * to access the values the pointers point to, and swap them using a temporary variable.