Alex Rivera | Logout

C++ creating arrays

Asked 2011-10-29T18:23:08.023
10

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

Edit
Report

1 Answer

1

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.

answered 2011-10-29T18:28:26.410

Your Answer