expression did not evaluate to a constant in C++ V

2019-02-25 08:25发布

问题:

I am running into error where in declaration of VLA is giving error of "expression did not evaluate to a constant" - I tried to declare int l,m,r,n1,n2 constant but still it doesn't work. While I am aware of concept that compiler would like to know fixed size array at compile time, however I have seen few implementation online where folks have implemented as below.

Additional wiki search enter link description here have shown not all version of C++ support it -

Question - how to make it work without creating dynamic memory allocation ?

template<typename T>
void mergesort<T>::_merge_array(int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    /* create temp arrays */
    int L[n1], R[n2];  // error -
}

回答1:

A strictly-conforming C++ implementation doesn't have variable-length arrays. Use std::vector instead:

#include <vector>

...

std::vector<int> L(n1), R(n2);


回答2:

In c++ you can't create static array without specifing the max limit/size of it at the time of coding, else compiler would generate error if you will do like :

main()
{
int size;
cout<<"Enter Size of Array : ";
cin>>size;
int myarray[size];   //here this will generate an error
....
...
..
}

because compiler does not know the actual size of static array to allocate memory for it at the time of execution and hence it can't allocate memory for it.

because static array take memory allocation from the Stack and Dynamic array takes memory allocation from the heap which is dynamic itself, which provides extra memory to a program at the time it is running.

Hope this will help you out why the concept of dynamic arrays were added.