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 are faster, so I wanted to use arrays)
thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
Just make sure you free the memory when you’re done, or you’ll get a memory leak:
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).