Struct and Union confusing behavior

I have this code declared in an H file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct ACTS_UInt16_Int16
{
	union
	{
		wtUInt16_t		m_value1;
		wtUInt32_t		m_combined_value;
	};
	wtInt16_t		m_value2;
};

struct PacketUInt16_Int16
{
	PacketHeader		m_header;
	ACTS_UInt16_Int16	m_data;
};


and i a CCP file :

1
2
3
4
	static short Data32BitChannel[07] = {0x02, 0x01, 0x24, 0x5301, 0xC914  };
	PacketUInt16_Int16 *pData = reinterpret_cast<PacketUInt16_Int16*>(Data32BitChannel);
	pData->m_data.m_value2 = 0xAAAA;
        *****Breakpoint******


at the breakpoint i hover over the Data32BitChannel and I see {0x02, 0x01, 0x24, 0x5301, 0xC914, 0xAAA }; instead of
{0x02, 0x01, 0x24, 0x5301, 0xAAAA };

Some one can explain to me this behavior.

NB:
when I comment the wtUInt32_t m_combined_value; it works just fine.

Thanks in advance for ur help.

regards,
waguila wrote:
when I comment the wtUInt32_t m_combined_value; it works just fine.


If you comment it where? Comments can't really affect the behaviour of a program ...

Are you really using structs?
Last edited on
When you have a union, the compiler has to account for all memory required for all members of the union. When you have a wtUint32_t and a wtUint16_t in the union, the union will take up the size of a wtUint32. The extra bytes are not accessible from the m_value1 field, but they do live in the object. When you comment out the larger field, the union only needs to account for the wtUint16_t member, so the memory lines up as you expect it to.
doug4 yeah this is what happens thank you for you help.
Topic archived. No new replies allowed.