Can't create float array with a variable name as size parameter

When trying to compile code that users a variable in the array subscript to set the size, CC gives the following error:

The code is as follows:

int main()
{

const int arrSize = numberVariables;
float tempArr[arrSize];

}


Any ideas on why CC is giving that error?
What is that error?
What is 'numberVariables' ?
I just try to codeblocks.org (GCC compiler) and there is no problem.


1
2
3
4
5
6
int main()
{
const int arrSize = 50;
float tempArr[arrSize];
  return 0;
}
D:\prog\cc\foo>gcc -Wall -pedantic -std=c89 a.c
a.c: In function 'main':
a.c:4: warning: ISO C90 forbids variable length array 'tempArr'
a.c:4: warning: unused variable 'tempArr'

In short, you are trying to do something illegal.

[edit] Oh, yeah, always turn on all warnings when compiling to get these kinds of error messages.
Last edited on
Try changing to 'static const int' instead of just 'const int'.
Wait, it gives an error while using a const int as the size? Impossible.
It isn't impossible -- it is not valid in C90.
Never mind. I misunderstood what const meant.
It doesn't have anything to do with the 'const'ness of the size. It has to do with the fact that the size of the array is being initialized from a value stored elsewhere in the program -- which is illegal in C90. Hence, the array is 'dynamic' because its size is not guaranteed to be fixed at compile time (whether const or not). Remember, const values are only indicated to be unchangable by your program. Oh, and here's a plug for const_cast.

Moreover, if you can create an array using some value stored elsewhere, what difference does it really make whether that value is const or not? The architecture to implement the allocation would be the same. Hence, it is a dynamic allocation.

If you want to be able to do this sort of thing, you must use a compiler that understands C99 or C++.
How come anyone is yet to mention dynamic allocation?
float *tempArr=new float[arrSize];
+1

Field "Content" too short: minimum is 3 characters
fooey
I'm surprised that someone didn't suggest this before the use of operator new to allocate the memory. The std::vector would be my first choice for a dynamic array.
std::vector<float> tempArr(arrSize, 0.0);
Topic archived. No new replies allowed.