返回指向静态局部变量的指针

nal*_*zok 0 c static declaration

当我编译这段代码时

#include <stdio.h>

int *foo();

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

int *foo()
{
        static int bar;
        return &bar;
}
Run Code Online (Sandbox Code Playgroud)

Clang给我看错:

static2.c:7:8: error: expression is not assignable
Run Code Online (Sandbox Code Playgroud)

为什么这是非法的?我想bar有静态存储持续时间,所以它的生命周期是整个程序的执行.虽然bar本身不可见main(),但指针应该能够修改它.

这个版本foo()也不起作用,Clang给了我同样的错误:

int *foo()
{
    static int bar;
    static int* ptr = &bar;
    return ptr;
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 6

由于运算符优先级(后缀增量,++高于取消引用*)(请参阅http://en.cppreference.com/w/cpp/language/operator_precedence),

    *foo()++;
Run Code Online (Sandbox Code Playgroud)

相当于:

    *(foo()++);
Run Code Online (Sandbox Code Playgroud)

这是无效的,因为返回值foo是指针并且foo()计算为临时指针.您不能递增或递减临时指针.

您可以使用以下方法修复它:

    (*foo())++;
Run Code Online (Sandbox Code Playgroud)