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.
std::unique_ptr<double> s(myfunction(x,y,2));, but honestly I'd usestd::vectorfrom the get-go for all the dynamic allocations in this code.x = {1, 1}valid syntax?std::unique_ptr<double[]>?