Search code examples
arrayscconstants

Constant value for the size of Array! How to make that?


Here is a part of the C code:

void merge(int arr[], 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];

    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    
.
.
.

For statement int L[n1],R[n2]; , I have this error:

expression must have a constant value

And this shot for better explication: enter image description here

I ran this code on Code::Blocks without any problem and totally clean! But on MSVC I have this problem.

I had this issue before and I could fix it but this time, I could not fix it and maybe I forgot the way!

As I know, there are two ways to deal with it: 1. Using #define 2. Use enum .

But for this special case, I think none of them can be helpful. Please help!


Solution

  • Variable length Arrays were added in C99.

    Microsoft C conforms to the standard for the C language as set forth in the 9899:1990 edition of the ANSI C standard

    MSVC is not a C99 compiler. You can dynamically allocate memory with malloc() and family.

    /* create temp arrays */
        int *L = malloc (n1 * sizeof *L);
        int *R = malloc (n2 * sizeof *R);
    
    /* Check the return value of `malloc().
    *  It returns `NULL` to signal failure.
    */
    
    /* some code here .... */
    
        free (R);
        free (L);