誰知道爲什麼輸出是這樣的?
儘管使用這樣的指針是錯誤的,但我仍然想明白爲什麼它的行爲如此。如何解釋這個奇怪的輸出?關於指針和臨時變量
int* foo()
{
int a=9;
int *p=&a;
//definitely not right to return a pointer to an invalid varible
return p;
}
int main(int argc, char* argv[])
{
int *p=foo();
cout<<*p<<endl;//9
cout<<*p<<endl;//2357228
*p=2;
cout<<*p<<endl;//2
(*p)++;
cout<<*p<<endl;//2357229
cout<<*p<<endl;//2357228
cout<<*p<<endl;//2357228
(*p)++;
cout<<*p<<endl;//2357229
cout<<*p<<endl;//2357228
return 0;
}
這就是未定義行爲的美妙之處。 – Mysticial
http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris
你對C++語言感興趣嗎?或者你對這種情況下編譯器產生的特定代碼感興趣嗎?如果前者,語言規範在這個問題上沒有什麼可說的,就不要這樣做。如果是後者,請看組件輸出。 –