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

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

问题描述:

#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?

C ++编译器只能在编译时已知的大小分配的数组。如果你想分配可变大小一块内存,使用运营商。

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.