当我从函数返回指针时,可以单独访问它的值。但是当使用循环输出该指针变量的值时,会显示错误的值。我哪里出错了,想不通。
#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++ 编译器应该对此发出警告,您应该注意这些警告。
对于它的值(value),这里是我如何在 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, ", "));
}
关于c++ - 从 C++ 中的函数返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969292/