c - 为什么我得到 "arithmetic of pointer type is required"?

标签 c pointers casting struct

在下面的代码中,当我将浮点指针类型转换为结构时出现错误,但如果我类型转换为其他内容,编译器不会报错。为什么要这样做?

typedef unsigned byte CELbool;
typedef struct {(...)} Color;
typedef struct {
    (...)
    Color color;
    CELbool b;
} Light;

Light _light;

void function(float *x) {
    _light.b = (CELbool)*x; // No error
    _light.color = (Color)*x; // (!) Used type 'Color' where arithmetic or pointer type is required
}

编辑:假设我有一个 *x 是指向颜色的指针,那么获取该颜色的正确方法是什么?我目前正在使用 Color c = *((Color *)(value)),但我认为这不是正确的方法。

最佳答案

您所做的转换不是从指针到整数或结构的转换,而是从 float 到整数和结构的转换。表达式

(CELbool)*x

转换 *x 的值(因为 x 是一个 float*,所以是一个 float ) 到 CELBool 中,您已将其定义为某个整数类型的 typedef。这种转换是可以的,因为 C 允许浮点值和整数值之间的转换,因为有一种合理的方法来进行转换。然而,第二个 Actor 是

(Color)*x

Color 是一个结构,C 没有定义浮点类型和 struct 之间的转换,就像它没有定义整数类型和 structs,因为通常没有合理的方法来进行这种转换。

关于“需要指针或算术类型”的错误的原因是因为 float 的转换需要是某种可以转换 float 的类型to,它可以是一些实值类型、整数类型或指针类型,因为 float 可以转换为指针(尽管这样做是一个非常糟糕的主意!)类型Color 不是编译器放置在那里的合理内容列表所期望的,因此会出现错误。

希望这对您有所帮助!

关于c - 为什么我得到 "arithmetic of pointer type is required"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594427/

相关文章:

c++ - “mblctr”不被识别为内部或外部命令、可操作程序或批处理文件。如何解决此问题?

c - 将地址传递给 C 中的函数

Swift:如何将 Optional ("Optional(str)") 转换为 Int

swift - 在 Swift 中将 NSNumber 转换为 NSTimeInterval

c - 总线错误: 10 in data generation in C

c - "[*]"(星号修饰符)在 C 中是什么意思?

c - 是否可以使Doxygen扩展枚举初始化程序?

c - 错误 : request for member xxxxxx in something not a structure or union

windows - 为什么系统在使用指针 Windows 时分配更多内存?

objective-c - 从 const void 转换为 char?