Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create static array with a size that is an execute-time constant?

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.

like image 942
jslap Avatar asked Oct 22 '10 14:10

jslap


People also ask

Can static array have variable size?

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.

Can we give size of array at run time?

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.

Can we change size of array at runtime in C?

Unlike static arrays, Dynamic arrays in C are allocated on the heap and we could change their size in runtime.

Can we declare array as static?

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.


1 Answers

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.)

like image 132
GManNickG Avatar answered Sep 23 '22 22:09

GManNickG