We all know the basic rules for static array:
int size = 20;
char myArray[size];
is not legal. And.
const int size = 20;
char myArray[size];
is OK.
But, what about this.
int f(const int size)
{
char myArr[size];
}
void main()
{
f(2);
f(1024);
}
MSVC says it is an error, gcc seems to compile and execute it fine.
Obviously, it is not portable, but should it be accepted?
Which compiler does the right thing in that situation?
Also, if it is permited by the compiler, should it be permited by good programming standards/practice?
EDITED: The idea is that I would want stack allocation for the speed, but I would not know at compile time the size of the array. I know that there is some other solutions, and that stack alloc would probably not be a significative optimization, but I think it is an interesting usage.
You cannot declare a static array of variable size because its space is allocated in the Data Segment (or bss segment in case of an uninitialized variable). Hence the compiler needs to know the size at the compile time and will complain if the size is not a constant.
Size of an array Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.
Unlike static arrays, Dynamic arrays in C are allocated on the heap and we could change their size in runtime.
Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.
No. C++ has no variable-length arrays. C99 does, and gcc allows it via extension.
Use a std::vector
.
Assuming you have profiled your application and found this to be a bottleneck, write a custom allocator that allocates from the stack and use that. If not, there's not a problem.
Stack allocation is very fast, but this likely isn't going to be a main concern in a real application. (You should have a custom memory management scheme in place that will performance close in speed to stack allocation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With