Referencing a union inside a structure using union tag gives incorrect address
Posted
by AlanKley
on Stack Overflow
See other posts from Stack Overflow
or by AlanKley
Published on 2010-04-13T03:37:13Z
Indexed on
2010/04/13
3:43 UTC
Read the original article
Hit count: 527
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.
© Stack Overflow or respective owner