简体   繁体   中英

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

Here is what I have tried:

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

But this tells me that n is not a constant expression, so I cannot use it to declare the array size. But if I try:

int fun1(vector<int> s)
{ 
    const int n = 10;
    int arr[n]; //<-----this works
}

then it's fine. Even if I make the vector s of type const, it still won't recognize the size as a constant expression. How do I go about this?

Declaring array by int arr[N]; the size N must be determined in compile-time (except for some compiler extensions which allow you to define them in run-time too). By the way, you can make it:

std::unique_ptr<int[]> arr (new int [n]);

// ... or ...

std::vector<int> arr(n);

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, ie 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<int> would almost certainly be a better approach. Unless you've got a good reason not to, I'd go with that.

For this, C++ has std::vector<int>(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM