Home > Mobile >  Variable length in a Simple Matrix c
Variable length in a Simple Matrix c

Time:10-13

I'm using VS 2019. In this code:

using namespace std;
int main()
{
    cout << "Inserisci la dimensione della matrice:";
    int DIM;
    DIM = 2;
    cin >> DIM;
        int v[DIM][DIM];
    return 0;
}

I Don't understand why in:

int v[DIM][DIM]; 

I've this error:

The expression must have a constant value. It is not possible to use the "DIM" variable value as a constant.

CodePudding user response:

In C , the size of an array must be a compile time constant. So you cannot write code like:

int n = 10;
int arr[n];    //incorrect

Correct way to write this would be:

const int n = 10;
int arr[n];    //correct

So we cannot use the input given by the user as the size of the array. That is why you are getting the mentioned error.

You can use std::vector in place of built in array to solve your problem.

CodePudding user response:

some compiler/c version doesn't support variable length arrays compile time. we can create dynamic array on heap. Below code works for you

using namespace std;
int main()

{
    cout << "Inserisci la dimensione della matrice:";
    int DIM;
    DIM = 2;
    cin >> DIM;
    int **v = new int*[DIM];
    for (int i=0;i<DIM;i  )
        v[i] = new int[DIM];
    // now you can use it as 2D array i.e
    v[0][0] = 12;
    cout<<v[0][0];
    return 0;
}
  •  Tags:  
  • c
  • Related