为什么foo((&i)++)给出Lvalue所需的错误.没有关联的数组

Akh*_*gla 6 c reference lvalue

我理解Lvalue的一些事情,但我不明白下面的代码是如何产生错误的:

#include<stdio.h>

void foo(int *);

int main() 
{
   int i=10;
   foo((&i)++);
}

void foo(int *p)
{
    printf("%d",*p);
}
Run Code Online (Sandbox Code Playgroud)

6:13:错误:左值作为增量操作数foo((&i)++); ^

kad*_*ina 2

x++ 结果如下。

1) read the value of x in to register.
2) increment the value of x
3) write the incremented value back to x (which means you are changing the value of x by '1')
Run Code Online (Sandbox Code Playgroud)

但你想要做的是 (&i)++ ,这意味着以下内容。

1) read address of i into register
2) increment the address by 1
3) write the incremented value in to address again? How you can change the address?
Run Code Online (Sandbox Code Playgroud)

如果要将存储在下一个地址中的整数发送到 foo(),则需要按如下方式递增。

int *p = &i + 1;
foo(p);
Run Code Online (Sandbox Code Playgroud)

但这可能会导致未定义的行为,因为您只知道存储 i 值的 i 地址。一旦你增加地址,你将得到下一个地址,它可能包含一些垃圾值。