0

Weird, very weird case. Consider the code:

int n = 50;
auto p1 = new double[n][5]; //OK
auto p2 = new double[5][n]; //Error

main.cpp: In function ‘int main()’:
main.cpp:17:26: error: array size in new-expression must be constant
auto p2 = new double[5][n]; //Error

main.cpp:17:26: error: the value of ‘n’ is not usable in a constant expression
main.cpp:15:8: note: ‘int n’ is not const

Can anyone explain why do I get a compile error on the second one but the first one works perfectly?

2
  • 1
    "gets a compile error", doesn't post the error. Commented Nov 23, 2017 at 14:05
  • 2
    It might help you to see how the compiler parses those lines. Commented Nov 23, 2017 at 14:08

2 Answers 2

7

With new double[n][5] you are allocating n values of type double[5].

With new double[5][n] you are allocating 5 variable-length arrays. And C++ doesn't have VLA's so that's invalid.

The solution, as ever, is to use std::vector:

std::vector<std::vector<double>> p2(5, std::vector<double>(n));

The above defines p2 to be a vector of vectors of double. It constructs p2 to have a size of 5 elements, where each element is initialized to a vector of n values.

Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is explained, incidentially with the exact example that you give (funny!?) on the new[] expression page on cppreference under the section "Explanation". See excerpt:

If type is an array type, all dimensions other than the first must be specified as positive integral constant expression (until C++14) converted constant expression of type std::size_t (since C++14), but the first dimension may be any expression convertible to std::size_t. This is the only way to directly create an array with size defined at runtime, such arrays are often referred to as dynamic arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.