2D数组似乎将值更改为c ++类成员

时间:2013-05-18 14:46:17

标签: c++ class pointers member

在我的程序中使用双指针指向数组时,我有一个奇怪的行为:

 /* 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 from _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 );
 }

事实是:双指针'_t1'正在从函数'readfile(...)'中分配和填充。这没关系,因为简单的'print'表示已从文件中正确读取了值。 现在,数组'_t2'被分配在A类构造函数中;当我从_t1开始填充_t2时,似乎数组_t1中的值已经改变,我不明白为什么! 在调用函数readfile(...)之后,对_t1的数组没有执行任何其他操作,但是当我在_t2的赋值期间打印它的值时,它们与第一次打印不同。我一直在想数组_t1已通过引用正确传递给函数readfile(...),可能我错过了什么!愿有人找到一些东西!!!

0 个答案:

没有答案