0

I am trying to code an algoritihm, and I was originally using dev C++ which allowed me to use a variable for an Array, however, I copied it over to visual studio community, and now it's broken throwing an error saying it needs a const.

Do you guys have any suggestions on a fix? I have been trying to look up a way to implement it into this.

void mergeSortOG(int inA[], int n)
{
    if (n == 0)
    {
        return;
    }
    
    int tempA[n]; //temporary array
    
    for (int i = 0; i < n; i++)
    {
        
        tempA[i] = inA[i];
    }
    
    mergeSort(tempA, 0, n, inA);
    
    for (int i = 0; i < n; i++)
    {
        inA[i] = tempA[i];
    }
}
user4581301
  • 31,330
  • 6
  • 30
  • 51
  • Have you looked at [this question](https://stackoverflow.com/q/5246900/8593689) and its answers? – Shane Bishop May 12 '22 at 01:10
  • 1
    Some compilers allow it, but [in general you can't](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). Use a [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead. – user4581301 May 12 '22 at 01:11
  • 1
    I suggest rephrasing "use a variable [for/in] an Array" as "use a variable for an array size", as it is not the elements of the array that you are talking about. – JaMiT May 12 '22 at 01:28

1 Answers1

0

I didn't test this (the std::copy_n is dubious) but here is one way of doing it:

void mergeSortOG(int inA[], int n) {
  if (!n) return;
  
  int* tempA = new int[n];

  std::copy_n(inA, n, tempA);
  mergeSort(tempA, 0, n, inA);
  std::copy_n(tempA, n, inA);
  
  delete[] tempA;
}

Unlike C, C++ doesn't have Variable Length Arrays.
You should probably use std::vector.

viraltaco_
  • 391
  • 2
  • 11
  • 1
    Some good reading on why you should NOT do this: [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – user4581301 May 12 '22 at 01:25