2
votes

I am aware that using reinterpret_cast to cast an array of unsigned char to a struct pointer can cause problems because of padding and ordering of bytes on different systems (like in this example)

struct SomeData
{
    unsigned char first;
    int second;
};

unsigned char data[5];
// SomeData might be more than 5 bytes because of padding
// We can't be sure second is valid, because of bytes ordering
SomeData* someData = reinterpret_cast<SomeData*>(data); 

But my question is for a struct having only unsigned char members

struct RGB
{
    unsigned char r;
    unsigned char g;
    unsigned char b;
};

unsigned char data[3];
RGB* rgbData = reinterpret_cast<RGB*>(data); 

In this case the struct RGB is kind of the equivalent of unsigned char[3], therefor I would assume there would be no padding. I have tested with g++ and msvc and no padding is added, is this guaranteed?

1
Note that the struct might have some alignment/padding. - Igor R.
With GCC you can force no padding by __attribute__((packed)) - nada

1 Answers

0
votes

While the reinterpret_cast is well-defined (in that you can reinterpret_cast back to the original type safely), accessing the structure members is undefined behavior by implication: there is no object of type RGB, so there cannot be a member of it to which to refer.

C explicitly and normatively describes circumstances for which the standard describes no behavior as undefined behavior; C++ merely implies the implication in a note, but it is after all the etymology of “undefined”.