Hello everyone,
I have a question. I want to create a function which takes as an input a file, read it and creates a 2D array. Dimensions of the array are not known and are written in the file.
The array has to be accessible out from the scoping of the function.
Right now my solutions is something like this:
double ** getmatrix(ifstream& InputFile) {
<read dimensions of the matrix from the file>
double **Mat;
// allocation of memory for the matrix
Mat= newdouble * [DIM1];
for i to DIM1
Mat[i]= newdouble [DIM2];
//Matrix values assignment
Mat[i][j]=blabla;
return Mat;
}
int main() {
ifstream ReadFile(file);
double **MAT;
double **MAT2;
MAT=getmatrix(ReadFile);
<Select new file position to get the matrix>
//Get new matrix
MAT2=getmatrix(ReadFile);
<operations with MAT and MAT2>
return;
}
Maybe is too complicated but I'm not expert in C++ programming...
This solution seems to work but 2 things:
1. Are the data of the matrix protected in the main? I mean, is it possible in this way that the allocation of memory for one variable overwrites data stored in my matrix?
2. Is it possible to do the same stuff in another/better way? I want to use the return for error management.
1. No, they are not protected and in large data sets it's perfectly resonable to expect that data from one array may be over written by the other.
2. Any one of the STL containers can help you accomplish this in C++, choosing which one to use will depend on what you plan on doing with the data later.