#include <iostream>
using namespace std;
int *GetSquare(int x)
{
int y = x;
y = y * y;
return &y;
}
int main()
{
const int n = 4;
int *p[n];
for (int j = 0; j < 2; ++j)
{
p[2 * j + 1] = new int[2];
for (int i = 0; i < 2; ++i)
p[2 * j + 1][i] = 2 * j + 1;
}
p[0] = GetSquare(2);
p[2] = GetSquare(4);
for (int j = 0; j < n; ++j)
{
for (int i = 0; i < 1; ++i)
cout << p[j][i] << " ";
cout << endl;
}
return 0;
}
當我幹這個代碼時,我得到輸出「4 1 16 3」。 而在編譯器中,我得到「16 1 3 3」 theres沒有辦法在哪裏我可以找到第一個輸出是16.我的代碼有什麼問題?沒有得到所需的輸出
有一兩件事我注意到:http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris 2015-03-13 19:08:34
請將您的標題改爲與您遇到的問題更相關的內容。 「沒有得到正確的輸出」幾乎適用於任何有史以來的軟件錯誤。 – Borgleader 2015-03-13 19:08:51
一個問題是你的'GetSquare'返回一個指向'GetSquare'本地的變量的指針。那很糟。你爲什麼不回傳價值?你是什麼意思,*當我幹這個代碼... *?它實際上應該做什麼? – lurker 2015-03-13 19:10:29