Union with pointers

I have a union with two pointers to different data types:

union{
    UCHAR *_rawData;
    RGB *_RGBData;
};
typedef struct RGB
{
    UCHAR red;
    UCHAR green;
    UCHAR blue;
}RGB;

later in code ...

_rawData = new UHCAR[126];
_RGBData = new _RGBData[42]; //3 times lower than rawData

So my question is: is such a union safe? Theoretically, both variables use 126 bytes, so it should be fine, but I'm not sure why I asked here

+4
source share
1 answer

The union itself is valid, but only one member of the association can be active at any time:

  • Two initializations, as later in the code, are completely wrong: the first pointer will be lost.
  • You must specify a way to determine which member is active.
+7
source

Source: https://habr.com/ru/post/1568061/


All Articles