views:

159

answers:

3

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.

+2  A: 

You should be writing:

char *pBuff = m_myStruct.m_Data.m_Buff;

I wish I knew how it was compiling as written.

Jonathan Leffler
Yeah, that's basically my question. Don't understand why that compiled or why it gave me the wrong offset. I am now using m_myStruct.m_Data.m_Buff but I was just wanting to understand the compiler's reasoning for the previous access method.
AlanKley
Are you sure it was compiling? Really sure? Can you check again, because I can see no legitimate interpretation for what you wrote, and would point a finger at the compiler thinking 'bug'.
Jonathan Leffler
@Jonathan and AlanKley: I've compiled Alan's example with several versions of MSVC++ and it compiles without error right up through today's VC2010 release, and the result of the expression is exactly as Alan described - as nonsensical as it may be. All other compilers I've tried give an appropriate error message.
Michael Burr
@Michael: thanks for the information - very intriguing (and more than a little surprising).
Jonathan Leffler
Thanks Michael. I'm glad I'm not going crazy. Since other compilers flag the code as an error I'm going to chalk it up as as a VC compiler bug!
AlanKley
+1  A: 

Don't you mean this?

char* pBuff = m_myStruct.m_Data.m_Buff;
Eddy Pronk
Why do you need a union? Please give some context.
Eddy Pronk
Yes, that's what I'm using now but I was seeking some insight on why the previous method worked the way it did.
AlanKley
Did the previous method compile? If so, can you print the pointer and edit your post?
Eddy Pronk
+2  A: 

It shouldn't compile. GCC barfs at this code with :)

union.cpp:17: error: ‘MyStruct::theData’ is not a base of ‘MyStruct’
Nikolai N Fetissov
That would have been nice in VS2008, then I wouldn't have had to debug the problem and I would have been alerted to add the proper declaration to access the data with. Thanks for checking it out.
AlanKley