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.theD开发者_运维知识库ata::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.
You should be writing:
char *pBuff = m_myStruct.m_Data.m_Buff;
I wish I knew how it was compiling as written.
It shouldn't compile. GCC barfs at this code with :)
union.cpp:17: error: ‘MyStruct::theData’ is not a base of ‘MyStruct’
Don't you mean this?
char* pBuff = m_myStruct.m_Data.m_Buff;
精彩评论