3

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 -
}
thedreamer
  • 319
  • 1
  • 5
  • 13
  • 1
    [gcc and clang support VLA in C++ as an extension while VS does not](http://stackoverflow.com/q/21273829/1708801). So strictly by the standard VS is correct. – Shafik Yaghmour Nov 23 '15 at 19:22
  • Many C++ compilers support that C99 feature in C++, but it is not valid C++. It also is a feature you should not be using for that purpose even if the compiler supported it and you didn't care about portability. Stack space is generally more limited than dynamic space. So don't expose your code to pointless stack overflows. Just use a dynamic allocation. – JSF Nov 23 '15 at 19:25

2 Answers2

5

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

#include <vector>

...

std::vector<int> L(n1), R(n2);
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • thank u - I think from all the answers it seems going for VLA through vectors or dynamic allocation only seems best option !!! – thedreamer Nov 23 '15 at 19:38
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.

Gaurav
  • 111
  • 3