0
0
C++programming~20 mins

Pointer and variable relationship in C++ - Practice Problems & Coding Challenges

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 and variable modification
What is the output of this C++ code snippet?
C++
#include <iostream>
int main() {
    int x = 10;
    int* p = &x;
    *p = 20;
    std::cout << x << std::endl;
    return 0;
}
A20
B10
CCompilation error
DUndefined behavior
Attempts:
2 left
💡 Hint
Remember that *p accesses the value pointed to by p.
Predict Output
intermediate
2:00remaining
Pointer reassignment effect
What is the output of this C++ code?
C++
#include <iostream>
int main() {
    int a = 5, b = 10;
    int* p = &a;
    p = &b;
    *p = 20;
    std::cout << a << " " << b << std::endl;
    return 0;
}
A5 20
B5 10
C20 20
D20 10
Attempts:
2 left
💡 Hint
Pointer p is changed to point to b before modifying *p.
Predict Output
advanced
2:00remaining
Pointer arithmetic and variable values
What is the output of this C++ code snippet?
C++
#include <iostream>
int main() {
    int arr[3] = {1, 2, 3};
    int* p = arr;
    *(p + 1) = 10;
    std::cout << arr[1] << std::endl;
    return 0;
}
A2
B10
CCompilation error
DUndefined behavior
Attempts:
2 left
💡 Hint
Pointer arithmetic moves the pointer to the next element.
Predict Output
advanced
2:00remaining
Pointer to pointer value change
What is the output of this C++ program?
C++
#include <iostream>
int main() {
    int x = 5;
    int* p = &x;
    int** pp = &p;
    **pp = 15;
    std::cout << x << std::endl;
    return 0;
}
A5
BCompilation error
C15
DUndefined behavior
Attempts:
2 left
💡 Hint
**pp accesses the value pointed to by the pointer p.
Predict Output
expert
2:00remaining
Pointer and variable relationship with const correctness
What is the output of this C++ code snippet?
C++
#include <iostream>
int main() {
    int x = 10;
    const int* p = &x;
    // *p = 20; // Uncommenting this line causes error
    x = 20;
    std::cout << *p << std::endl;
    return 0;
}
AUndefined behavior
B10
CCompilation error
D20
Attempts:
2 left
💡 Hint
const int* means you cannot change the value through the pointer, but the variable itself can change.