Click here to Skip to main content
15,882,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I keep receiving an error saying "Expression must have a constant value the value of variable 'n1' cannot be used as a constant ". I don't know what am I use suppose to do to fix it.

C++
void merge(DataType theArray[], int first, int mid, int last)

int i, j, k;
int n1 = mid - first + 1;   
int n2 = last - mid;

 int L1[n1], R1[n2];  //n1, n2 are giving me the same problem mentioned above

for (i = 0; i < n1; i++)
    L1[i] = theArray[first + i];
for (j = 0; j < n2; j++)
    R1[j] = theArray[mid + 1 + j];



What I have tried:

I've tried putting const int.
I've tried deallocating
Posted
Updated 25-Oct-21 16:41pm

You don't say what compiler/OS you are using, but since this above snippet is accepted by gcc, I am guessing that you are using MSVC, which does not support variable length arrays. You will have to use dynamic memory allocation to create an appropriately sized array. With modern C++, that is normally done using std::unique_ptr
C++
#include <memory>
void merge(DataType theArray[], int first, int mid, int last)
{
    int n1 = mid - first + 1;
    int n2 = last - mid;

    auto L1 = std::unique_ptr<DataType[]>(new DataType[n1]);
    auto R1 = std::unique_ptr<DataType[]>(new DataType[n2]);
    /* etc */
}
Note that in your code, L1, R1 have types int but theArray has type DataType. Unless DataType is an numeric type (int, float, etc), then the assigments in the loops should be generating errors as well.
 
Share this answer
 
Comments
k5054 25-Oct-21 22:46pm    
Addendum: Sometimes I think the Universe likes synchronicity. Posted earlier in Insider News : https://www.codeproject.com/Messages/5839439/Cplusplus-Smart-pointers-and-arrays
CPallini 26-Oct-21 2:18am    
5.
C++
void merge(DataType theArray[], int first, int mid, int last)
// did you forgot the '{' here ?
int i, j, k;
int n1 = mid - first + 1;   
int n2 = last - mid;

 int L1[n1], R1[n2];  //n1, n2 are giving me the same problem mentioned above

for (i = 0; i < n1; i++)
    L1[i] = theArray[first + i];
for (j = 0; j < n2; j++)
    R1[j] = theArray[mid + 1 + j];
// and the '}' at the end of function ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900