Should I worry about the alignment during pointer casting?

前端 未结 7 1345
遇见更好的自我
遇见更好的自我 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:47

    Update: I overlooked the fact that indeed smaller types may be unaligned relatively to a larger one, like it may be in your example. You can aleviate that issue by reversing the way you cast your array : declare your array as an array of int, and cast it to char * when you need to access it that way.

    // raw data consists of 4 ints
    int data[4];
    
    // here's the char * to the original data
    char *cdata = (char *)data;
    // now we can recast it safely to int *
    i1 = *((int*)cdata);
    i2 = *((int*)(cdata + sizeof(int)));
    i3 = *((int*)(cdata + sizeof(int) * 2));
    i4 = *((int*)(cdata + sizeof(int) * 3));
    

    There won't be any issue on array of primitives types. The issues of alignment occur when dealing with arrays of structured data (struct in C), if the original primitve type of the array is larger than the one it is casted to, see the update above.

    It should be perfectly ok to cast an array of char to an array of int, provided you replace the offset of 4 with sizeof(int), to match the size of int on the platform the code is supposed to run on.

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

    Note that you will get endianness issues only if you share that data somehow from one platform to another with a different byte ordering. Otherwise, it should be perfectly fine.

提交回复
热议问题