Return 从 C++ 中的函数指向数组的指针?

Return a pointer to array from a function in C++?

我是一名初级程序员,我有一个关于 return 指向 C++ 中双精度数组指针的函数的问题。该函数接受两个数组并将每个元素相加,就像向量的总和一样。

我认为正确的做法是....

double *myfunction(double *x, double *y, int n){
  double *r = new double[n];
  for(int i=0;i<n;i++){
    r[i] = x[i]+y[i];
  }
  return r;
}

问题是我在 main 函数的 while 循环中使用了这个函数,就像这样

int main(){
  double *x, *y, *s;
  x = new double[2];
  y = new double[2];
  x = {1,1};
  y = {2,2};

  while(/*some condition */){
    /*some process...*/

    s = myfunction(x,y, 2);

    /*some process...*/
  }

  delete[] x;
  delete[] y;
  delete[] s;
}

我的问题是内存泄漏是怎么回事?每次我使用 "myfunction" (在 while 循环内)我为变量 "s" 保留内存,这意味着如果 while 循环执行 5 次,那么程序为变量保留 5 倍的内存变量 "s"?

有没有办法做到这一点(return 从函数指向数组的指针并在循环中使用该函数)??

先谢谢你。

为避免内存泄漏,您需要在获取后立即使用 s,并在用完后将其删除。

 int main(){
      double *x, *y, *s;
      x = new double[2];
      y = new double[2];
      x = {1,1};
      y = {2,2};

      while(//some condition ){
        s = myfunction(x,y, 2);
        //do some process here
        delete[] s;
      }
      delete[] x;
      delete[] y;

    }

我想说 myfunction 更正确的写法是:

std::vector<double> myfunction(double *x, double *y, int n){
  std::vector<double> r;
  r.reserve(n);
  for(int i=0;i<n;i++){
    r.push_back(x[i]+y[i]);
  }
  return r;
}

这样,您就不必担心内存泄漏,您的 while 循环可以是:

while (/* some condition*/) {
    std::vector<double> s = myfunction(x, y, 2);
    // whatever
}

您问的是:

Each time I use "myfunction" (inside the while-loop) I reserve memory for the variable "s", that means that if the while-loop is executed 5 times, then the program reserves 5 times the memory for the variable "s"?

答案是

您还问过:

Is there exists a way to do this (return a pointer to arrays from a function and use that function inside a loop)??

答案是。您需要添加代码来删除 returned 内存,

  while( /*some condition */){
    s = myfunction(x,y, 2);

    // Use s

    // Now delete s.
    delete[] s;
  }

比必须处理 newdelete 更好的解决方案是 return 来自 myfunctionstd::vector。然后,您无需担心管理内存。即