LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Find the Error · Question 4

Error: a function returning a C array Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

int[3] make() {
    int a[3] = {1, 2, 3};
    return a;
}

int main() {
    std::cout << make()[0] << '\n';
    return 0;
}
  • A make must be static
  • B Functions cannot return C arrays; return std::array<int, 3> or std::vector<int> instead Correct
  • C The array must be initialised with ()
  • D main cannot index a call
Correct Answer: Option B

Even returning a pointer to a would be wrong, because the local array dies at the end of the function. std::array<int, 3> make() { return {1, 2, 3}; } is correct.

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