I am trying to declare two arrays, one 2D and one 1D. I know the dimensions need to be const values. So the const value is assigned from the return value of a function call. That goes well, but when I use the derived value to declare the array, COMPILE errors! WHY???
Here is my code:
int populateMatrixFromFile(string fname) {
std::ifstream fileIn;
int s = determineDimensions(fname); // return value (CONST INT)
const int size = s; // assign to const
cout << "Value returned from determineDimensions(): " << size << endl;
if (size > 10){
cout << "Maximum dimensions for array is 10 rows and 10 columns. Exiting" << endl;
return 1;
}
fileIn.open(fname.c_str(), ios::in); //opened for reading only.
float aMatrix[size][size]; // ERROR
float bMatrix[size]; // ERROR
BUT it works here:
// assign the pth row of aMatrix to temp
const int alen = sizeof (aMatrix[p]) / sizeof (float);
float temp[alen]; // WORKS!!!
for (size_t i = 0; i < alen; i++) {
temp[i] = aMatrix[p][i];
}
Thanks for all help.
The compiler enforces this rule about a constant size of an array because it allocates the needed memory at compile time. In otherwords, all values needed to calculate the size of the array must be known at compile-time. In your first example, this is not the case, so the compiler complains.
If you really need to have dynamically sized arrays, you should use pointers and the new[] operator to allocate the array. You will also need to remember to use the delete[] operator to return the memory to the system and avoid any memory leaks.