Initialize array size from another array value

#include<iostream> using namespace std; const int vals[] = {0, 1, 2, 3, 4}; int newArray[ vals[2] ]; //"error: array bound is not an integer constant" int main(){ return vals[2]; } //returns 2 if erroneous line is removed 

Why is this not working?

+4
source share
3 answers

The C ++ compiler can only allocate an array with a size known at compile time. If you want to allocate part of memory with a variable size, use the new operator.

+5
source

Unfortunately, you cannot do this in standard C ++, because vals[2] not a constant expression! In the following standard, you would have constexpr (implemented in g ++ 4.6) to easily request compilation:

 #include<iostream> using namespace std; constexpr int vals[] = {0, 1, 2, 3, 4}; int newArray[ vals[2] ]; // vals[2] is a constant expression now! int main(){ return vals[2]; } 
+10
source

It is possible that the value of the const expression is not known even at compile time. For example, you can initialize a constant with something returned by a function, for example

 const int size = rand(); // random size 

So this is not how you think

+5
source

All Articles