开发者

Referencing a union inside a structure using union tag gives incorrect address

开发者 https://www.devze.com 2022-12-26 08:53 出处:网络
I had a need to declare a union inside a structure as defined below: struct MyStruct { intm_DataType; DWORDm_DataLen;

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号