-1

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.

2 Answers2

2

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.

Jason
  • 36,170
  • 5
  • 26
  • 60
-1

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;
}
Afzal Ali
  • 880
  • 8
  • 25
  • As far as I know, C++ doesn't suport VLAs at all. C does support them and some C++ compilers extend that support to C++ when compiled in non-strict mode. – Ulrich Eckhardt Oct 12 '21 at 17:13
  • Set your compilers to *strict* conforming to the ANSI/ISO standard and see if VLAs pass. :-) – Thomas Matthews Oct 12 '21 at 17:30
  • If you are going to dynamically allocate memory, consider the case of allocating one contiguous block of memory (`DIM * DIM`) then casting or treating as a 2d array. – Thomas Matthews Oct 12 '21 at 17:32