0

I'm fairly new to programming and I am having trouble initializing an array with a const int. so far for the code I have is this:

int temp = 0;
temp += valuesVec.size();
int SIZE = temp; 
int valuesArray[SIZE];

I am trying to make an array with the same number of elements as a vector that read a file and store all the values. the errors it gives me are:

Error   1   Expected constant expression.
Error   2   error C2466: cannot allocate an array of constant size 0    
Error   3   error C2133: 'valuesArray' : unknown size   
Error   4   IntelliSense: expression must have a constant value

all the errors lead back to: int valuesArray[SIZE]; printing SIZE gave me the value 1118.

I know I am probably doing something stupid and probably forgot some fundamental rule but... Until someone points it out I will be pouring over my book.

4

2 回答 2

2

静态数组的大小只能用非零常量值指定。如果在编译时大小未知,那么您应该使用动态数组。

int * valuesArray = new int [SIZE];
...
delete[] valuesArray;

请确保使用正确的 delete[] 运算符。

或者更好地使用std::vector

于 2013-11-12T05:38:54.620 回答
0

SIZE不是编译时常量(至少不是,除非valuesVec是),所以你不能静态声明一个数组SIZE作为它的大小。

您可以尝试手动分配它:

int* valuesArray = new int[SIZE];

如果你记得的delete[]话。或者你可以简单地制作另一个向量:

std::vector<int> valuesArray(SIZE);
于 2013-11-12T05:40:22.340 回答