[英]Returning Pointer from a Function in C++
当我从函数返回指针时,可以单独访问其值。 但是,当使用循环输出该指针变量的值时,将显示错误的值。 我在犯错误的地方,无法弄清楚。
#include <iostream>
#include <conio.h>
int *cal(int *, int*);
using namespace std;
int main()
{
int a[]={5,6,7,8,9};
int b[]={0,3,5,2,1};
int *c;
c=cal(a,b);
//Wrong outpur here
/*for(int i=0;i<5;i++)
{
cout<<*(c+i);
}*/
//Correct output here
cout<<*(c+0);
cout<<*(c+1);
cout<<*(c+2);
cout<<*(c+3);
cout<<*(c+4);
return 0;
}
int *cal(int *d, int *e)
{
int k[5];
for(int j=0;j<5;j++)
{
*(k+j)=*(d+j)-*(e+j);
}
return k;
}
您正在返回一个指向局部变量的指针。
k
在堆栈上创建。 当cal()
退出时,将取消堆栈堆栈,并释放该内存。 之后引用该内存会导致未定义的行为(如此处精美说明: https : //stackoverflow.com/a/6445794/78845 )。
您的C ++编译器应就此警告您,并且应注意这些警告。
对于它的价值,这是我将如何在C ++中实现的方法:
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
int main()
{
int a[] = {5, 6, 7, 8, 9};
int b[] = {0, 3, 5, 2, 1};
int c[5];
std::transform (a, a + 5, b, c, std::minus<int>());
std::copy(c, c + 5, std::ostream_iterator<int>(std::cout, ", "));
}
int k[5]
数组在堆栈上创建。 因此,当它超出范围时会从cal
返回而被销毁。 您可以使用第三个参数作为输出数组:
void cal(int *d, int *e, int* k)
{
for(int j=0;j<5;j++)
{
*(k+j)=*(d+j)-*(e+j);
}
}
像这样致电cal
:
int a[]={5,6,7,8,9};
int b[]={0,3,5,2,1};
int c[5];
cal (a, b, c); // after returning from cal, c will be populated with desired values
正如其他人指出的那样,您正在返回一个指向局部变量的指针,这是未定义的行为。 但是,真正的问题是您需要返回一个数组,并且C样式数组已损坏。 用std::vector<int>
替换数组,忘记指针(因为您正在处理值),代码将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.