C++ array initialization by reference through function -
i'm working on project requires many dynamically sized 2d arrays need accessible across functions. code i'm working on uses pointers double** dynarray
this.
r = ...; // rows of matrix, unknown prior runtime c = ...; // columns of matrix, unknown prior runtime double** dynarray;
after checking existing code found arrays being initialized this:
double** dynarray = new double*[r]; for(int r=0; r<r; r++){dynarray[r] = new double[c];}
in order improve readability write method above. here's came allocate
void initialize2d(double*** data, int r, int c){ (*dynarray) = new double*[r]; for(int r=0; r<r; r++){ (*dynarray)[r] = new double[c]; for(int c=0; c<c; c++){ (*dynarray)[r][c] = 0; } } }
and free memory respectively:
void free2d(double*** data, int r, int c){ for(int r=0; r<r; r++){ delete[] (*data)[r]; } delete *data; }
i intended use these methods this:
r = ...; // rows of matrix, unknown prior runtime c = ...; // columns of matrix, unknown prior runtime double** dynarray; initialize2d(&dynarray, r, c); /* stuff*/ free2d(&dynarray,r,c);
after implementing these functions ran valgrind , found qualifies
- definitely lost, sometimes
- possibly lost.
what problem, , proper way initialize through function reference?
write functions following way
double ** initialize2d( int r, int c ) { double **dynarray = new double *[r]; ( int r = 0; r < r; r++ ) { dynarray[r] = new double[c](); } return dynarray; } void free2d( double **data, int r ) { ( int r = 0; r < r; r++ ) delete [] data[r]; delete [] data; }
and call functions following way
double** dynarray = initialize2d( r, c ); /* stuff*/ free2d( dynarray, r ); dynarray = nullptr;
take account use standard container std::vector<std::vector<double>>
instead of dynamically allocate arrays yourself.
Comments
Post a Comment