简体   繁体   中英

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

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 -
}

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

#include <vector>

...

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

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.

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