0

I looked for C++ examples of Merge sort shown below. When I tried to compile it I get errors about two temporary arrays L[n1], R[n2]. I've read that an array should have fixed size, if not, we make it dynamic int* tab = new int[n1] for instance. But I've seen many examples like this below everywhere, so why this code below is working for other people?

int Merge(int A[],int p, int q,int r)     
{
    int n1,n2,i,j,k;  

    n1=q-p+1;
    n2=r-q;      

    int L[n1],R[n2];

    for(i=0;i<n1;i++)
    {
        L[i]=A[p+i];
    }
...
NGC 6543
  • 67
  • 1
  • 1
  • 6
  • some compiler offer it as extension – 463035818_is_not_an_ai May 25 '20 at 15:01
  • 1
    We don't use `int* tab = new int[n1];`, we use `std::vector tab(n1);`. – molbdnilo May 25 '20 at 15:18
  • This is not standard conform C++. C in contrast to C++ actually allows this. This is either C code or is using a compiler extension as idclev pointed out. – Eric May 25 '20 at 15:23
  • From what I recall GCC allows variable length arrays, while other compilers such as Visual Studio (or older Microsoft compilers) do not. Note that variable length arrays are allocated from the stack, which would in the case of Visual Studio, translates into `int *L = _alloca(n1*sizeof(int));`. For other compiles it's just alloca() instead of _alloca(). Allocating from the stack will result in stack overflow for a large array. I would be better to have the calling code or an entry helper function to do a one time allocation of the working array, and use indexes (or pointers) for the parameters, – rcgldr May 26 '20 at 14:15

0 Answers0