我有以下导致-Wincompatible-pointer-types
警告的代码:
union SensorData
{
uint64_t raw_sensor_data;
struct
{
uint16_t humidity_data;
uint16_t temperature_data;
};
} sensor_data;
/* ... Bunch of other code ...*/
uint8_t *raw_sensor_data_bytes = &sensor_data.raw_sensor_data;
uint8_t checksum = raw_sensor_data_bytes[0];
uint8_t sum = 0;
for (uint8_t i = 1; i < 8; i++)
{
sum += raw_sensor_data_bytes[i];
}
这是结果错误:
warning: initialization of 'uint8_t *' {aka 'unsigned char *'} from incompatible pointer type 'uint64_t *' {aka 'long long unsigned int *'} [-Wincompatible-pointer-types]
88 | uint8_t *raw_sensor_data_bytes = &sensor_data.raw_sensor_data;
| ^
我想我明白为什么错误被触发:这是因为我有一个指针,预计是指向一个8位整数,而在现实中它是指向一个64位整数;然而,这是一个很好的理由(我目前认为)。我需要将64位整数分成8位段,所以我认为创建一个指针将会很好,实际上,将64位整数分成8个8位段;然而,这样做会导致前面提到的警告。是否有一种更合适的方法来做我正在尝试做的事情,从而摆脱警告,或者我是否可以以某种方式简单地覆盖警告,或者我必须忽略它?
将对象指针转换为指向char
或unsigned char
(或同等类型)的指针以访问对象的单个字节是定义良好的,只要转换是通过显式强制转换进行的:
uint8_t *raw_sensor_data_bytes = (uint8_t *)&sensor_data.raw_sensor_data;