从另一个数组值初始化数组大小

时间:2022-04-08 01:53:04
#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 doesn't this work?

为什么这不起作用?

3 个解决方案

#1


5  

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

C ++编译器只能在编译时分配一个已知大小的数组。如果要分配可变大小的内存,请使用new运算符。

#2


10  

Unfortunately you can't do that in standard C++ because vals[2] is not a constant expression! In the coming standard you would have constexpr(implemented in g++ 4.6) to request compile-time evaluation easily:

不幸的是,你无法在标准C ++中做到这一点,因为vals [2]不是一个常量表达式!在即将推出的标准中,您将拥有constexpr(在g ++ 4.6中实现)以轻松地请求编译时评估:

#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];
}

#3


5  

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

const表达式的值有可能在编译时甚至都不知道。例如,您可以使用函数返回的内容初始化常量,例如

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

So it is not that constant as you might think

所以它不像你想象的那样恒定

#1


5  

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

C ++编译器只能在编译时分配一个已知大小的数组。如果要分配可变大小的内存,请使用new运算符。

#2


10  

Unfortunately you can't do that in standard C++ because vals[2] is not a constant expression! In the coming standard you would have constexpr(implemented in g++ 4.6) to request compile-time evaluation easily:

不幸的是,你无法在标准C ++中做到这一点,因为vals [2]不是一个常量表达式!在即将推出的标准中,您将拥有constexpr(在g ++ 4.6中实现)以轻松地请求编译时评估:

#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];
}

#3


5  

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

const表达式的值有可能在编译时甚至都不知道。例如,您可以使用函数返回的内容初始化常量,例如

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

So it is not that constant as you might think

所以它不像你想象的那样恒定