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()
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<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.
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);