當我編譯這段代碼,返回指針的靜態局部變量
#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;
}