Should I worry about the alignment during pointer casting?

前端 未结 7 1347
遇见更好的自我
遇见更好的自我 2020-11-28 05:47

In my project we have a piece of code like this:

// raw data consists of 4 ints
unsigned char data[16];
int i1, i2, i3, i4;
i1 = *((int*)data);
i2 = *((int*         


        
7条回答
  •  难免孤独
    2020-11-28 06:37

    It's not alright, really. The alignment may be wrong, and the code may violate strict aliasing. You should unpack it explicitly.

    i1 = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24;
    

    etc. This is definitely well-defined behaviour, and as a bonus, it's also endianness-independent, unlike your pointer cast.

提交回复
热议问题