Home > Software engineering >  Dealing with an `-Wincompatible-pointer-types` warning
Dealing with an `-Wincompatible-pointer-types` warning

Time:05-08

I have the following code which is causing the -Wincompatible-pointer-types warning:

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];
}

This is the resulting error:

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;
      |                                      ^

I think that I understand why the error is getting triggered: it's because I have a pointer that expects to be pointing to an 8 bit integer, when in reality it is pointing to a 64-bit integer; however, this is for (what I currently think) a good reason. I need to split that 64-bit integer into 8-bit segments, so I thought that it would be fine to create a pointer that would, in effect, divide the 64-bit integer into 8 8-bit segments; however, doing this is causing the aformentioned warning. Is there a more proper way to do what I am trying to do that would get rid of the warning, or is it possible for me to just simply override the warning in some way, or do I just have to ignore it?

CodePudding user response:

It is well-defined to convert an object pointer to a pointer to a char or unsigned char (or equivalent) to access the individual bytes of an object, as long as the conversion happens via an explicit cast:

uint8_t *raw_sensor_data_bytes = (uint8_t *)&sensor_data.raw_sensor_data;
  • Related