如何将 typedef 结构转换为 uint8_t 参数

how to cast typedef struct to uint8_t argument

我有一个定义的函数:

uint32_t match_data(uint8_t * data_in, uint16_t size_data_in);

我在其中尝试使用以下 typedef 结构作为参数

typedef struct
{
uint8_t chars[5]
uint8_t ADC;
}Data

Data input;

input.chars[0] = 65;
input.chars[1] = 66;
input.chars[2] = 67;
input.chars[3] = 68;
input.chars[4] = 69;
input.ADC = 255;

match_data((uint8_t *)input, sizeof(input)); 

match_data() 函数返回 'Data' 类型的操作数,其中需要算术或指针类型

如何将 typedef 结构转换为 uint8_t?如果我将它用作参考并且我得到相同的错误

如果我只使用 char 数组,我可以直接转换它,但当使用 typedef 结构时则不能

您需要转换结构对象的地址,而不是结构对象本身:

match_data((uint8_t *)&input, sizeof(input));

这是有效的,因为对象的地址保证等于第一个成员的地址(即 chars)。

但是请注意,访问其他数据成员是 unsafe/undefined 行为,即通过这样的指针 ADC。这是因为编译器可能会在成员之间引入填充字节,并且访问这样的填充区域是未定义的行为(因为填充区域处于不确定状态;例如,参见 online C standard draft):

J.2 Undefined behavior ...The value of an object with automatic storage duration is used while it is indeterminate.

所以实际上我会说你应该直接通过 chars

match_data(input.chars, sizeof(input.chars));