Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union with pointers

Tags:

c++

unions

I have an union with 2 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 it safe to make union like this? Theoretically both variables use 126 bytes so it should be ok but I'm not sure so I asked here

like image 739
Quest Avatar asked Feb 12 '23 08:02

Quest


1 Answers

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

  • Doing the two initialisation as later in the code is hence definitively wrong: the first pointer will be lost.
  • You have to fin a way to determine which of the member is active.
like image 154
Christophe Avatar answered Feb 20 '23 04:02

Christophe