Challenge - 5 Problems
Pointer Arithmetic Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of pointer arithmetic with arrays
What is the output of the following C++ code?
C++
#include <iostream> int main() { int arr[] = {10, 20, 30, 40}; int* p = arr; std::cout << *(p + 2) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that pointer arithmetic moves by the size of the data type.
✗ Incorrect
The pointer p points to the first element of arr (10). Adding 2 moves it two integers ahead, pointing to 30.
❓ Predict Output
intermediate2:00remaining
Pointer subtraction result
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { int arr[] = {5, 10, 15, 20, 25}; int* p1 = &arr[4]; int* p2 = &arr[1]; std::cout << p1 - p2 << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Pointer subtraction gives the number of elements between two pointers.
✗ Incorrect
p1 points to arr[4], p2 to arr[1]. The difference is 4 - 1 = 3, but pointer subtraction counts elements, so output is 3.
❓ Predict Output
advanced2:00remaining
Pointer arithmetic with char arrays
What does this program print?
C++
#include <iostream> int main() { char str[] = "hello"; char* p = str; std::cout << *(p + 4) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Pointer arithmetic on char arrays moves one character at a time.
✗ Incorrect
The pointer p points to 'h'. Adding 4 moves to the fifth character 'o'.
❓ Predict Output
advanced2:00remaining
Pointer arithmetic with void pointers
What error does this code produce?
C++
#include <iostream> int main() { int x = 10; void* p = &x; p = p + 1; return 0; }
Attempts:
2 left
💡 Hint
Pointer arithmetic requires knowing the size of the pointed type.
✗ Incorrect
You cannot do arithmetic on void pointers because the compiler doesn't know the size of the data type.
🧠 Conceptual
expert2:00remaining
Pointer arithmetic and array indexing equivalence
Which option correctly explains why *(arr + i) is equivalent to arr[i] in C++?
Attempts:
2 left
💡 Hint
Think about how array indexing is defined in terms of pointers.
✗ Incorrect
The C++ standard defines arr[i] as *(arr + i), so they are exactly the same operation.