gpt4 book ai didi

c - 为什么 foo((&i)++) 给出 Lvalue required 错误。没有关联的数组

转载 作者:太空狗 更新时间:2023-10-29 17:24:48 26 4
gpt4 key购买 nike

我了解一些关于左值的事情,但我不明白下面的代码是如何出错的:

#include<stdio.h>

void foo(int *);

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

void foo(int *p)
{
printf("%d",*p);
}

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

最佳答案

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')

但是您要尝试做的是 (&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?

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

int *p = &i + 1;
foo(p);

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

关于c - 为什么 foo((&i)++) 给出 Lvalue required 错误。没有关联的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47233646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com