首页 > 解决方案 > 在c++中复制数组的内容

问题描述

以下简化的代码不正确。我想写入提供给的数组 YY_ ,operator()想知道怎么做?似乎问题在于它假设复制指针复制数组的内容?!

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;
  }
 };

标签: c++arrayspointers

解决方案


是的,指针可能很困难。我对此表示怀疑,但我没有时间检查我的代码,而且这里的人比我更有资格做到这一点的资格要高出 100,000 倍......但我们到了。

您需要将指向 YY 的指针作为参数传递给 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;
  }
 };

祝你好运,我希望这会有所帮助。我在工作中没有做太多的运算符重载,所以我很有可能错过了一个 12 岁的孩子会在这里抓住的东西。


推荐阅读