简体   繁体   中英

How do i initialize an array in a fucntion whose length is given by a formal parameter in C++

for example,

int func(int len){
int arr[len];
}

this doesn't compile. with the error

expression did not evaluate to a constant.

so, how can i initialize an array in such a way?

In fact the function deals with a variable length array. The C++ Standard does not allow to use variable length arrays though some compilers have their own language extensions that support variable length arrays.

So in any case you have to allocate the array dynamically/. Either you can do this using the operator new as it is shown in the demonstrative program below

#include <iostream>
#include <memory>
#include <numeric>

void func( size_t n )
{
    std::unique_ptr<int[]>a( new ( std::nothrow ) int[n] );

    if ( a )
    {
        std::iota( a.get(), a.get() + n, 0 );

        for ( size_t i = 0; i < n; i++ ) std::cout << a[i] << ' ';
        std::cout << '\n';
    }
}

int main() 
{
    func( 10 );

    return 0;
}

The program output is

0 1 2 3 4 5 6 7 8 9 

Or you can use the standard container std::vector that itself allocates dynamically memory.

#include <iostream>
#include <vector>
#include <iterator>
#include <numeric>

void func( size_t n )
{
    std::vector<int> v( n );

    std::iota( std::begin( v ), std::end( v ), 0 );

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';
}

int main() 
{
    func( 10 );

    return 0;
}

The program output is the same as shown above.

Because your variable given could be dynamic I would use a vector:

#include <vector>

int func(const int len){
std::vector<int> arr(len);
}

if you want to avoid std::vector, you would use const (not required, but in the control structure you would not change the value):

int func(const int len){
  int arr[len];
}

It least my compiler g++ 9.2 accepts that, but only if the feature Variable Length Array (VLA) is enabled. That is not part of the C++ standard though.

Static arrays like arr[] must have known length at compile time. You need to dynamically allocate, so use: Int* arr = new int[len];

Basically, u need to allocate the array dynamically, therefore u can use new or malloc, in this case,

int fun(int len)
{
int *ar; 
ar=new int [len];
for(int i=0;i<len;i++)
{
cin>>ar[i];
}
}

Now its all upto you what you want from your code now . remmber if u are using malloc include header file in c or c++

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