简体   繁体   中英

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

I am a beginning programmer and I have a question about a function that returns a pointer to array of doubles in C++. The function takes two arrays and adds up each element, like in a sum of vectors.

I think the correct way to do is....

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

The problem is that I use that function in a while-loop in the main function like this

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

My question is what about the memory leak? 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)??

Thank you in advanced.

To avoid memory leak you need to use s as soon as you get it and delete it once you are done.

 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;

    }

I'd say the more correct way to write myfunction is:

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

That way, you don't have to worry about memory leaks, and your while loop can just be:

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

You asked:

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"?

The answer is Yes .

You also asked:

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

The answer is Yes . You need to add code to delete the returned memory,

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

    // Use s

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

A better solution than having to deal with new and delete is to return a std::vector from myfunction . Then, you don't need worry about managing memory. That is the answer by Barray

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