简体   繁体   English

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

[英]Returning pointer to static local variable

When I compile this code, 当我编译这段代码时,

#include <stdio.h>

int *foo();

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

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

Clang shows me an error: lang告诉我一个错误:

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

Why it's illegal? 为什么是非法的? I suppose bar have static storage duration, so its lifetime is the entire execution of the program . 我想bar具有静态的存储期限,因此它的生存期是程序的整个执行过程 Although bar itself isn't visible to main() , a pointer should be able to modify it. 尽管bar本身对main()不可见,但是指针应该能够对其进行修改。

This version of foo() doesn't work too, and Clang gives me the same error: 这个版本的foo()也不起作用,Clang给了我同样的错误:

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

Due to operator precedence (suffix increment, ++ , is higher than dereference, * ) (See http://en.cppreference.com/w/cpp/language/operator_precedence ), 由于运算符优先级(后缀增量++大于取消引用* )(请参见http://en.cppreference.com/w/cpp/language/operator_precedence ),

    *foo()++;

is equivalent to: 等效于:

    *(foo()++);

That is invalid since the return value of foo is a pointer and foo() evaluates to a temporary pointer. 这是无效的,因为foo的返回值是一个指针,而foo()值是一个临时指针。 You cannot increment or decrement a temporary pointer. 您不能增加或减少临时指针。

You can fix it by using: 您可以使用以下方法修复它:

    (*foo())++;

Its illegal because of the way you are using the return value. 由于您使用返回值的方式,它是非法的。 bar is visible and can be used in main() bar是可见的,可以在main()

The problem is with 问题出在

*foo()++;

You need to provide the expression in parentheses 您需要在括号中提供表达式

(*(foo()))++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM