[英]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.