Possible Duplicate:
Is there a way to initialize an array with non-constant variables? (C++)
I have the following code:
vector<vector<vec2>> vinciP;
int myLines = -1;
myLines = drawPolyLineFile("vinci.dat", vinciP);
if (myLines > -1)
{
cout << "\n\nSUCCESS";
vec2 vPoints[myLines];
for (int i = 0; i < NumPoints; ++i)
{
vPoints[i] = vinciP[0][i];
}
}
I'm getting an error on the line 'vec2 vPoints[myLines];' that says expressions must have a constant value. I don't understand why I'm getting this err开发者_如何学编程or, any help?
Is it because myLines could be negative? idk.
vec2 vPoints[myLines];
Since myLines
is not a const expression ((which means, it is not known at compile-time), so the above code declares a variable length array which is not allowed in C++. Only C99 has this feature. Your compiler might have this as an extension (but that is not Standard C++).
The solution to such commom problem is : use std::vector<T>
as:
std::vector<vec2> vPoints(myLines);
It should work now.
Is it because myLines could be negative?
No, It is because myLines
is not a compile time constant.
Explanation:
vec2 vPoints[myLines];
Creates an array of variable length, where myLines
value will be determined at Run-time.
Variable length arrays are not allowed in C++. It was a feature introduced in C99, and C++ Standard does not support it. Some C++ compilers support it as an extension though but it is nevertheless non standard conforming.
For C++ size of an array should be known at compile time and hence must be compile time constant. myLines
is not a compile time constant and hence the error.
You should use a std::vector
vec2 vPoints[myLines];
Array size must be a compile time constant. myLines
is not a compile time constant. Instead, allocate the memory using new or even better to use std::vector
.
C++ does not have variable-length arrays. The size of an array must be determined at compile-time. The value of myLines
is only known at runtime, so this won't work.
To have arrays whose size is only known at runtime, use std::vector
.
std::vector<vec2> vPoints(myLines);
You are getting that error because static arrays need a static (constant) size. Since the number of components in your vPoints
is dynamic, consider using a dynamic array instead. Or better yet stick with vector
.
精彩评论