[英]Compare function argument of typedef struct with its instance declaration in C
我正在尝试编写以下 function,
#define CW 0
#define CCW 1
typedef struct
{
uint8_t dir;
uint8_t sr;
uint8_t pwml;
uint8_t en;
uint8_t state;
uint8_t runstate;
uint8_t endstop_status;
} Motor_Params;
Motor_Params Motor_M1;
Motor_Params Motor_M2;
Motor_Params Motor_M3;
Motor_Params Motor_M4;
void Home_Motor(Motor_Params *motor, uint8_t dir)
{
if (dir == CCW)
{
// Start moving motor towards the endstop.
while (motor->endstop_status != 1)
{
if (motor == Motor_M1)
Start_M1_CCW();
else if (motor == Motor_M2)
Start_M2_CCW();
else if (motor == Motor_M3)
Start_M3_CCW();
else if (motor == Motor_M4)
Start_M4_5_CCW();
}
}
}
我正在尝试将Motor_Params *motor
与其实例声明进行比较,这样我就可以将此 fn 用于多个电机。 当我尝试编译这个时,我得到,
error: invalid operands to binary == (have 'Motor_Params *' and 'Motor_Params')
if (motor == Motor_M1)
如何将Motor_Params *motor
与其任何实例声明进行比较?
像这样的 if 语句中的比较
if (motor == Motor_M1)
没有意义。 也就是说 motor 是Motor_Params *
类型的指针,而Motor_M1
是 Motor_Params 类型的Motor_Params
。
如果要比较Motor_Params
类型的两个对象,则需要根据您对结构的相等操作的含义比较结构类型的两个对象的数据成员。 也就是说,没有为结构定义内置运算符 ==。
请注意,当 function 定义依赖于全局变量时,这是一个坏主意。 而不是这些声明
Motor_Params Motor_M1;
Motor_Params Motor_M2;
Motor_Params Motor_M3;
Motor_Params Motor_M4;
你可以声明一个数组,例如
Motor_Params Motors[4];
并将这个数组作为参数传递给 function。
目前您正在比较指针和实际结构。 你必须选择其中之一。
要比较指针,请将&
添加到结构中以获取它们的指针:
if (motor == &Motor_M1)
Start_M1_CCW();
else if (motor == &Motor_M2)
Start_M2_CCW();
else if (motor == &Motor_M3)
Start_M3_CCW();
else if (motor == &Motor_M4)
Start_M4_5_CCW();
要比较结构的值,请将*
添加到motor
以取消引用:
if (*motor == Motor_M1)
Start_M1_CCW();
else if (*motor == Motor_M2)
Start_M2_CCW();
else if (*motor == Motor_M3)
Start_M3_CCW();
else if (*motor == Motor_M4)
Start_M4_5_CCW();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.