#include <stdio.h>
int ∗addition(int a, int b){
int c = a + b ;
int ∗d = &c ;
return d ;
}
int main (void) {
int result = ∗(addition(1, 2));
int ∗resultptr = addition(1, 2);
printf(」result = %d\n」, ∗resultptr);
printf(」result = %d\n」, result);
return 0 ;
}
這會給出正確的答案。但奇怪的是,一旦我交換了最後兩個printf()的順序,就會給出異常的答案。爲什麼顛倒printf()的順序會產生不同的輸出?
printf(」result = %d\n」, result);
printf(」result = %d\n」, ∗resultptr);
這是爲什麼?是否因爲printf()的一些內部實現?
我打開了-Wall選項,但沒有顯示警告。
謝謝你的回答!這是我在stackoverflow上的第一個問題。
但是爲什麼顛倒順序會給出不同的答案?如果這是由於未定義的返回一個局部變量的行爲,爲什麼第一個程序給出了正確的答案,但第二個程序不能,而唯一的區別是printf()的順序?
是的,因爲通過返回局部變量的地址,並在函數返回後使用它,您將進入未定義行爲的領域。不,它不是因爲printf的內部實現。 – SuperSaiyan 2014-09-01 06:28:11
請開啓,閱讀並理解編譯器警告。 – 2014-09-01 06:28:56
可能的重複[可以訪問局部變量的內存超出其範圍?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) 。關注於C++,但是同樣適用於C. – juanchopanza 2014-09-01 06:30:29