+ 1

Why can't an array's size be defined with a variable?

25th Jun 2016, 5:54 PM
Aceitunarabe
Aceitunarabe - avatar
3 Antworten
+ 1
you can if you declare that variable constant. const int validsize = 6; int myarray[validsize]; or with a function if you declare it constexpr: constexpr int f() { return 5; } int myarray[f()];
25th Jun 2016, 6:11 PM
Garme Kain
Garme Kain - avatar
+ 1
This is because you allocate it on the stack or on the static / global space. For these the compiler has to know their size at compile time. Truly dynamic allocation is done on the heap via "new" operator.
25th Jun 2016, 6:14 PM
Stefan
Stefan - avatar
0
Okey thx both of you!
25th Jun 2016, 6:17 PM
Aceitunarabe
Aceitunarabe - avatar