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

May 13, 2009 at 4:01pm
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?
May 13, 2009 at 4:06pm
What is that error?
What is 'numberVariables' ?
May 13, 2009 at 4:12pm
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;
}
May 13, 2009 at 4:15pm
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 May 13, 2009 at 4:16pm
May 13, 2009 at 5:04pm
Try changing to 'static const int' instead of just 'const int'.
May 13, 2009 at 5:16pm
Wait, it gives an error while using a const int as the size? Impossible.
May 13, 2009 at 5:21pm
It isn't impossible -- it is not valid in C90.
May 13, 2009 at 5:55pm
Never mind. I misunderstood what const meant.
May 13, 2009 at 6:16pm
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++.
May 13, 2009 at 6:25pm
How come anyone is yet to mention dynamic allocation?
float *tempArr=new float[arrSize];
May 13, 2009 at 8:14pm
+1

Field "Content" too short: minimum is 3 characters
fooey
May 13, 2009 at 11:34pm
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.