简体   繁体   中英

Compile error with non-constant array declaration, C++

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM