问题描述
我是一个开始的程序员,我有一个关于函数的问题,它返回一个指向C ++中double类型的指针。该函数接受两个数组,并将每个元素相加,如向量总和。
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;
}
我的问题是如何处理内存泄漏?每次我使用myfunction(在while循环中)时,我为变量s保留内存,这意味着如果while循环执行5次,那么程序为变量s保留5倍的内存?
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)??
先进的感谢。
推荐答案
我会说更正确的方式来写 myfunction
是:
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;
}
这样,您不必担心内存泄漏,而您while循环可以是:
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
}
这篇关于从C ++中的函数返回指向数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!