Is it possible to allow a user to enter an array size with a keyboard?

后端 未结 5 1924
萌比男神i
萌比男神i 2021-01-13 10:21

Is it possible to allow the user to enter the size of an array with a keyboard?

I know that arrays can\'t change size. The only solution I could think of is this:

5条回答
  •  青春惊慌失措
    2021-01-13 11:12

    No, arrays cannot be variably sized in C++. The code you have there will not compile, because the value of a constant has to be evaluated at compile-time.

    You might try the std::vector class instead and use the resize method, or pass the size through the constructor. Although, depending on what you need, maybe you can just let it grow naturally by using push_back.

    A lower-level alternative is to use dynamically allocated arrays:

    int userSize;
    cin >> userSize;
    int* array = new int[userSize];
    

提交回复
热议问题