简体   繁体   中英

Copy the contents of the array in c++

The simplified following code is not correct. I want to write into the array YY_ that is supplied to operator() , was wondering how can do it? Seemingly the issue is that it is assuming that copying pointers copies the contents of the array?!

double *computeY(double const *const *xx){
  const int i0 = 0;
  const int i1 = 1;
  static double YY[2];
  YY[0] = xx[i0][0] + xx[i1][0];
  YY[1] = xx[i0][1] + xx[i1][1];
  return YY;
} 

struct computeYFunctor{
   computeYFunctor(){}
   bool operator()(double const *const *xx_, double* YY_) const{
     YY_ = computeY(xx_);
     return true;
  }
 };

Yea, pointers can be difficult. I'm taking a swag at this but I don't have time to check my code, and there are going to be folks here 100,000 times more qualified to do this better then I am... but here we are.

You need to pass the pointer to YY as an argument to computeY()

void computeY(double const *const *xx, double *YY ){
  const int i0 = 0;
  const int i1 = 1;                // array is  (pointer math)
  YY[0] = xx[i0][0] + xx[i1][0];   // YY[0] is *(YY+0)=val
  YY[1] = xx[i0][1] + xx[i1][1];   // YY[1] is *(YY+1)=val
  // So the two lines YY[0] reached out to the addresses YY+0 and YY+1
  // And modified the data.
} 

struct computeYFunctor{ 
   computeYFunctor(){}
   bool operator()(double const *const *xx_, double* YY_) const{
     computeY(xx_, YY_);
     return true;
  }
 };

Good Luck and I hope this helps. I don't do much operator overloading in my work, so there is a good chance I'm missing something a 12 year old would catch here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM