LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 18

Reading a 2D array through a flat pointer Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>

int main() {
    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int* p = &m[0][0];
    std::cout << p[4] << ' ' << *(m[1] + 2) << ' ' << sizeof(m) << ' ' << sizeof(m[0]) << '\n';
    return 0;
}
  • A 5 6 24 12 Correct
  • B 5 6 24 8
  • C 4 6 24 12
  • D 5 3 24 12
Correct Answer: Option A

Rows are stored one after another, so element 4 of the flat sequence is m[1][1] = 5. m[1] + 2 points to m[1][2] = 6. The whole array is 24 bytes; one row is 12.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links