处理“-Wincompatible-pointer-types”警告
Dealing with an `-Wincompatible-pointer-types` warning
我有以下导致 -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
(或等效)的指针以访问对象的各个字节是well-defined,只要转换通过显式转换发生:
uint8_t *raw_sensor_data_bytes = (uint8_t *)&sensor_data.raw_sensor_data;
我有以下导致 -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
(或等效)的指针以访问对象的各个字节是well-defined,只要转换通过显式转换发生:
uint8_t *raw_sensor_data_bytes = (uint8_t *)&sensor_data.raw_sensor_data;