c++ array – expression must have a constant value

When creating an array like that, its size must be constant. If you want a dynamically sized array, you need to allocate memory for it on the heap and you’ll also need to free it with delete when you’re done:

//allocate the array
int** arr = new int*[row];
for(int i = 0; i < row; i++)
    arr[i] = new int[col];

// use the array

//deallocate the array
for(int i = 0; i < row; i++)
    delete[] arr[i];
delete[] arr;

If you want a fixed size, then they must be declared const:

const int row = 8;
const int col = 8;
int arr[row][col];

Also,

int [row][col];

doesn’t even provide a variable name.

Leave a Comment