2D Array seems to change values as c++ class member -
i have got strange behavior when using double pointer array in programm this:
/* in a.h */ class a{ private: int _n; int _m; int _p; int _dim; int** _t1; int** _t2; public: ~a(); a(); a(const a& a); a& operator=(const a& a); a(int n, int m, std::string filename); }; int readfile(int* p, int* dim, int*** t1, std::string filename); /* in a.cpp */ a::a(int n, int m, std::string filename){ _n = n; _m = m; _t1 = null; _t2 = null; int ierr; ierr = readfile(&_p, &_dim, &_t1, filename); // print _t1[i][j] here : no problem // fill _t2 _t1 : problem!! _t2 = new int*[_p]; // check allocation for(int k = 0; k < _p; k++){ _t2[k] = new int[_dim]; } for(int k = 0; k < _p; k++){ for(int j = 0; j < _dim; j++){ _t2[k][j] = 0; } } int in, ie, nv; for(int k = 0; k < _p; k++){ nv = _t1[k][_dim]; if(nv == dim){ for(int in = 0; in < nv; in++){ in = _t1[k][in]; ie = _t2[in][_dim]; _t2[in][ie] = k; _t2[in][_dim] += 1; } } } } int readfile(int* p, int* dim, int*** t1, std::string filename){ std::ifstream fid; std::string line; std::stringstream pline; fid.open(filename.c_str(), std::ifstream::in); if( !fid.is_open() ){ fprintf(stderr, "error : can't open %s ...\n", filename.c_str() ); exit( -1 ); } getline(fid, line); pline.str(line); pline >> (*p); getline(fid, line); pline.str(line); pline >> (*dim); *t1 = new int*[(*p)]; // check allocation for(int k = 0; k < *p; k++){ (*t1)[k] = new int[(*dim)]; } int j; for(int k = 0; k < *p; k++){ getline(fid, line); pline.str(line); j = 0; while( pline >> (*t1)[k][j] ){ j += 1}; } fid.close(); return ( 0 ); }
the fact is: double pointer '_t1' being allocated , filled function 'readfile(...)'. ok since simple 'print' shows values have been read file. now, array '_t2' allocated inside class constructor; when start filling _t2 _t1, appears values in array _t1 have changed, , don't figure out why! after calling function readfile(...), nothing else performed on array _t1, when print value during assignment of _t2, no more same first print. i've been thinking array _t1 has been passed correctly function readfile(...) reference, may i'm missing something! may find something!!!
Comments
Post a Comment