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

后端 未结 3 1505
我在风中等你
我在风中等你 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:25

    For this, C++ has std::vector(n), which retains most of the semantics of a traditional C array but also adds a lot of benefits (dynamic allocation being one, resizing is another, algorithm support is yet another one). Even when your underlying code requires a C array, you can still use the vector and pass an address of the first element down (they are guaranteed to be contiguous).

    Typically, std::vector uses heap for underlying storage, so on one hand you are better protected from stack overflows (pun intended), on the other hand, your code now uses dynamic allocation.

提交回复
热议问题