可能重複:
Can a local variable's memory be accessed outside its scope?
why does this function return garbage value很簡單的C++的基本代碼
爲什麼這個簡單的代碼返回垃圾?
char *output()
{
char o[2] = "A";
return o;
}
int main()
{
std::cout << output();
}
可能重複:
Can a local variable's memory be accessed outside its scope?
why does this function return garbage value很簡單的C++的基本代碼
爲什麼這個簡單的代碼返回垃圾?
char *output()
{
char o[2] = "A";
return o;
}
int main()
{
std::cout << output();
}
因爲你返回一個指向無效的內存 - o
被破壞時output
回報。
您有幾種選擇:
malloc
)動態分配內存,複製"A"
到這個內存,並返回其地址return "A";
附:當然,你可以使用std::string
,你不會有這個問題。或者使用進/出參數,而不是返回。
o爲output()
局部變量所以它有範圍和壽命時間只在函數內部。並作爲函數返回一個內存地址被返回其刪除存儲的地址。
,如果它被反饋的節目已經值會因方法「的價值迴歸」的工作。
如果您需要正確的輸出而不是默認內存說明符auto
您需要使用其他內容如static
或extern
內存分配或動態內存分配。
http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope在這裏看到了明確的答案,使用函數變量超出範圍。 –
而這一次也應該是有幫助http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question –
你的編譯器應該也警告您關於使用局部變量的地址。 – nijansen