C++ creating arrays

后端 未结 7 1164
一个人的身影
一个人的身影 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:34

    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;
    

提交回复
热议问题