gpt4 book ai didi

c - 为什么编译器不生成错误 "lvalue required"?

转载 作者:太空狗 更新时间:2023-10-29 15:21:44 26 4
gpt4 key购买 nike

根据我的理解,在下面代码中标记为“第 2 行”的行中,表达式 (*ptr)++ 应该生成“需要左值”错误,因为 *ptr 的计算结果为 i=1 的常量值,这不是左值?

那么为什么程序能成功运行呢?还是我的概念有问题?如果是,请赐教。

int main(void)
{
int i;
int *ptr = (int *) malloc(5 * sizeof(int));

for (i=0; i<5; i++)
*(ptr + i) = i;

printf("%d ", *ptr++); //line 1
printf("%d ", (*ptr)++); //line 2
printf("%d ", *ptr); //line 3
printf("%d ", *++ptr); //line 4
printf("%d ", ++*ptr); //line 5
}

最佳答案

你误会了。 (*ptr) 的结果 左值,可以在其上应用后增量运算符。

所以,在你的情况下,

 printf("%d ", (*ptr)++); //line 2

很好。

引用 C11 标准,第 6.5.3.2 章,地址和间接运算符(强调我的)

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.

FWIW,如果 *ptr 不是左值,您也会因为编写类似 *ptr = 5 的内容而出错,不是吗?

关于c - 为什么编译器不生成错误 "lvalue required"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398970/

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