2016-02-09 50 views
0

當我編譯這段代碼,返回指針的靜態局部變量

#include <stdio.h> 

int *foo(); 

int main() 
{ 
     *foo()++; 
     return 0; 
} 

int *foo() 
{ 
     static int bar; 
     return &bar; 
} 

鏘顯示我的錯誤:

static2.c:7:8: error: expression is not assignable 

爲什麼這是非法的?我認爲bar有靜態存儲的時間,所以它的生命週期是整個執行程序。儘管bar本身對main()不可見,但指針應該能夠對其進行修改。

這的foo()版本沒有工作過,並鏘給了我同樣的錯誤:

int *foo() 
{ 
    static int bar; 
    static int* ptr = &bar; 
    return ptr; 
} 

回答

6

由於運算符優先級(後綴增量,++表達式中使用,是高於解引用,*)(見http://en.cppreference.com/w/cpp/language/operator_precedence),

*foo()++; 

相當於:

*(foo()++); 

即無效由於foo返回值是一個指針和foo()計算爲一個暫時指針。您不能遞增或遞減臨時指針。

您可以通過使用修復:

(*foo())++; 
2

它非法的,因爲的方式,您正在使用的返回值。 bar是可見的,並且可以在main()

問題是與

*foo()++; 

您需要提供在括號

(*(foo()))++;