Referencing a union inside a structure using union tag gives incorrect address
- by AlanKley
I had a need to declare a union inside a structure as defined below:
struct MyStruct
{
int m_DataType;
DWORD m_DataLen;
union theData
{
char m_Buff [_MAX_PATH];
struct MyData m_myData;
} m_Data;
};
Initially, I tried accessing the union data as follows (before I added the m_Data declaration):
MyStruct m_myStruct;
char* pBuff = m_myStruct.theData::m_Buff;
This compiles but returns to pBuff a pointer to the beginning of the MyStruct structure which caused me to overwrite the m_DataType & m_DataLength members when I thought I was writing to the m_Buff buffer.
I am using Visual Studio 2008. Can anyone explain this unexpected behavior? Thanks.