gpt4 book ai didi

c - 收到错误 : cannot take the address of an rvalue of type 'int'

转载 作者:太空狗 更新时间:2023-10-29 17:03:08 27 4
gpt4 key购买 nike

我尝试用新的编译器编译旧代码并得到下一个错误:

error: cannot take the address of an rvalue of type 'int'

这是一个包含 2 行的示例 - 一行编译,另一行给出错误

struct mstct {
int myfield;
int myfield2[5];
int myfield3[5];
};

typedef struct mstct db_data_px;

int foo(int a, int b, int c){

//the next code compiles successfully.
unsigned val1 = ((18 == c) ? ((unsigned) & (((db_data_px *) 0)->myfield)) : ((unsigned) & (((db_data_px *) 0)->myfield3[b]))); //successes


//the next code is failing
unsigned val2 = (unsigned) & ((18 == c) ? (((db_data_px *) 0)->myfield) : (((db_data_px *) 0)->myfield3[b]));
return 0; // failing
}

为什么第一行编译成功而第二行编译失败?为什么我需要在两个 select 表达式中都强制转换 (unsigned) & 而仅在 select 表达式被赋值后才强制转换是不够的?

最佳答案

在你的代码中

   ((18 == c) ? (((db_data_px *) 0)->myfield) : (((db_data_px *) 0)->myfield3[b]))

是一个不产生左值的条件表达式。

上面的表达式为您提供了一个右值(非左值),您不能对其使用 & 运算符。

详细说明,引用 C11 标准,章节 §6.5.3.2,地址和间接运算符

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

OTOH,对于条件运算符的结果类型,第 6.5.15 章,脚注

A conditional expression does not yield an lvalue.

试想一下,&5,不可能。

关于c - 收到错误 : cannot take the address of an rvalue of type 'int' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35041861/

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