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.

3
  • 6
    What does "Constant Variable" mean to you? Commented Nov 12, 2013 at 5:28
  • Not the same thing it means to the compiler. :) Commented Nov 12, 2013 at 5:28
  • Use a std::vector. Use an array only if you have a good reason. Commented Nov 12, 2013 at 11:43

2 Answers 2

2

Size of a static array can only be specified with a nonzero constant value. If on the compile time the size is unknown then you should use dynamic array.

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

Please make sure using proper delete[] operator.

Or better use std::vector

Sign up to request clarification or add additional context in comments.

3 Comments

Remove the new/delete part, it makes this answer worse, not better. It’s error-prone, complicated and not necessary. And it certainly won’t help OP.
According to the author's proficiency was given the answer. STL might be confusing for him so far.
new/delete is more confusing. Despite what people think, the standard library is elementary C++. new/delete is not.
0

SIZE is not a compile-time constant (at least not unless valuesVec is), so you can not statically declare an array with SIZE as its size.

You can try manually allocating it:

int* valuesArray = new int[SIZE];

if you remember to delete[] it. Or you can simply make another vector:

std::vector<int> valuesArray(SIZE);

1 Comment

Remove the new/delete part, it makes this answer worse, not better. It’s error-prone, complicated and not necessary. And it certainly won’t help OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.