1

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?

Kalcifer
  • 1,211
  • 12
  • 18

1 Answers1

2

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;
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Ahh, so casting `&sensor_data.raw_sensor_data` to `(uint8_t)` says that `&sensor_data.raw_sensor_data` address no longer points to the address of a 64-bit integer, but instead to an 8-bit integer. at the location of the 64-bit integer? What I'm still confused with, is why they both seem to work just fine. What woudl be the case where they wouldn't work that gives reason to the warning? – Kalcifer May 07 '22 at 20:52
  • @Kalcifer The cast basically says "yes I meant to do that", though in general you want to avoid casts as they could mask real problem in some cases. – dbush May 07 '22 at 20:54
  • ahhh okay that makes sense. Could you give an example of when they would cause a problem? – Kalcifer May 07 '22 at 20:55