Pointers quiz

Answer each question to see whether you got it right and why. Your answers are saved in this browser.

0 correct · 0 / 23 answered
  1. Q1Reading and writing

    What does this print?

    int x = 10;
    int* p = &x;
    *p += 5;
    x *= 2;
    std::cout << *p;
  2. Q2Declarations

    After int* p, q;, what is the type of q?

  3. Q3Declarations

    In int* p = &x; the * dereferences p.

  4. Q4Aliasing

    What are a and b at the end?

    int a = 10, b = 20;
    int* p = &a;
    int* q = p;
    p = &b;
    *p = 99;
  5. Q5Aliasing

    Given int a = 5, b = 5; int* p = &a; int* q = &b;, what do p == q and *p == *q evaluate to?

  6. Q6Aliasing

    What are a and b after line 5? (Practice sheet Q1)

    int a = 4, b = 9;
    int* p = &a;
    int* q = p;
    *q += 3;      // 1
    q = &b;       // 2
    *p = *q - 2;  // 3
    p = q;        // 4
    *p += a;      // 5
  7. Q7Pointer states

    An uninitialised local pointer like int* p; is automatically nullptr.

  8. Q8Pointer states

    Checking if (p != nullptr) before dereferencing protects you from dangling pointers.

  9. Q9Pointer arithmetic

    What does this print?

    int a[] = {10, 20, 30, 40};
    int* p = a;
    ++p;
    p += 2;
    std::cout << *p;
  10. Q10Pointer arithmetic

    int a[4] starts at address 0x1000 and sizeof(int) == 4. What address does a + 3 hold?

  11. Q11Pointer arithmetic

    With int a[] = {10, 20, 30, 40}; int* first = a; int* last = a + 3;, what is last - first?

  12. Q12Pointer arithmetic

    For int a[4];, which of these is legal?

  13. Q13Pointer arithmetic

    What is *p + *q at the end? (Practice sheet Q2)

    int a[] = {3, 5, 7, 9, 11};
    int* p = a + 1;
    int* q = a + 4;
    *p = *q - *(p + 1);
    ++p;
    --q;
  14. Q14Functions

    Calling void reset(int* p) { p = nullptr; } sets the caller's pointer to nullptr.

  15. Q15Functions

    What is the final state? (Practice sheet Q3)

    void move(int* p, int* target) { *p += 3; p = target; }
    
    int x = 6, y = 10;
    int* p = &x;
    move(p, &y);
    *p += 2;
  16. Q16Functions

    Which signature lets a function make the caller's pointer point somewhere else?

  17. Q17Functions

    What is wrong with this function?

    double* bad() {
        double s = 26.48;
        return &s;
    }
  18. Q18Functions

    findMax returns a pointer to the first maximum element. The caller runs *findMax(a, 4) = 0; on {4, 9, 2, 9}. What is the array now? (Practice sheet Q4)

  19. Q19Structs and classes

    p is a Student*. What does *p.gpa do?

  20. Q20Structs and classes

    What is the only difference between struct and class in C++?

  21. Q21Templates

    Calculator<T>::divide() returns a / b. What does Calculator<int>(5, 2).divide() return?

  22. Q22Templates

    Given Number<int> n(7);, the line Number<double>* q = &n; is a compile error.

  23. Q23Ownership

    Which statement about std::unique_ptr is true?