san*_*box 0 c++ arrays pointers
当我从函数返回指针时,可以单独访问其值.但是当使用循环输出该指针变量的值时,会显示错误的值.在我犯错的地方,无法弄明白.
#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;
}
Run Code Online (Sandbox Code Playgroud)
您正在返回指向局部变量的指针.
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, ", "));
}
Run Code Online (Sandbox Code Playgroud)