Why can\'t I do something like this:
int size = menu.size;
int list[size];
Is there anyway around this instead of using a vector? (arrays a
C++ does not allow variable length arrays. The size must be known at compile-time. So you can't do that.
You can either use vectors or new
.
vector<int> list;
or
int *list = new int[size];
If you go with the latter, you need to free it later on:
delete[] list;
arrays are faster, so I wanted to use arrays
This is not true. Where did you hear this from?
first of all, vectors aren't significantly faster. as for the reason why you cant do something like this:
the code will allocate the array on the stack. compilers have to know this size upfront so they can account for it. hence you can only use constants with that syntax.
an easy way around is creating the array on the heap: int list = new int[size];
Don't forget to delete[]
later on.
However, if you use a vector and reserve the correct size upfront + compile with optimization, there should be little, to absolutely no overhead.
The size must be known at compile-time, since the compiler needs to know how much stack space will be needed to allocate enough memory for it. (Edit: I stand corrected. In C, variable length arrays can be allocated on the stack. C++ does not allow variable length arrays, however.)
But, you can create arrays on the heap at run-time:
int* list = new int[size];
Just make sure you free the memory when you're done, or you'll get a memory leak:
delete [] list;
Note that it's very easy to accidentally create memory leaks, and a vector is almost for sure easier to use and maintain. Vectors are quite fast (especially if you reserve()
them to the right size first), and I strongly recommend using a vector instead of manual memory-management.
In general, it's a good idea to profile your code to find out where the real bottlenecks are than to micro-optimize up front (because the optimizations are not always optimizations).
AFAIK In C++03, there are no variable-length-arrays (VLA):
you probably want to do this:
const int size = menu.size;
int list[size]; // size is compile-time constant
or
int *list = new int[size]; // creates an array at runtime;
delete[] list; // size can be non-const
In C++, the length of an array needs to be known at compile time, in order to allocate it on the stack.
If you need to allocate an array whose size you do not know at compile time, you'll need to allocate it on the heap, using operator new[]
int size = menu.size;
int *list = new int[size];
But since you've new'd memory on the heap, you need to ensure you properly delete it when you are done with it.
delete[] list;
Since list
is allocated on the stack, its size has to be known at compile time. But here, size
is not known until runtime, so the size of list
is not known at compile time.