Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ array - expression must have a constant value

Tags:

c++

arrays

I get an error when I try to create an array from the variables I declared.

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

Why do I get this error:

expression must have a constant value.

like image 997
Nicholas Kong Avatar asked Feb 09 '12 22:02

Nicholas Kong


1 Answers

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.

like image 90
Foggzie Avatar answered Oct 21 '22 11:10

Foggzie