C++ creating arrays

后端 未结 7 1179
一个人的身影
一个人的身影 2021-01-11 17:49

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

7条回答
  •  庸人自扰
    2021-01-11 18:30

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

提交回复
热议问题