How can I declare an array inside a function according to the size of a parameter?

后端 未结 3 1506
我在风中等你
我在风中等你 2021-01-13 07:51

Here is what I have tried:

int fun1(vector s)
{ 
    const int n = s.size();
    int arr[n]; //<----want to declare an array of length s.size()         


        
3条回答
  •  我在风中等你
    2021-01-13 08:13

    When you declare an array like this

    int arr[n];
    

    the compiler will allocate memory on the stack for it. In this case the C++ standard requires that n is known at compile time, i.e. it must be const.

    The answer to your question is to get the memory from the heap at run time like this:

    int* arr = new int[n];
    

    In this case the memory is allocated at run time and so the value of n doesn't need to be known until run time. If you use this approach don't forget to free up the memory when you're done with:

    delete [] arr;
    

    However, as the comments suggest, using a std::vector would almost certainly be a better approach. Unless you've got a good reason not to, I'd go with that.

提交回复
热议问题