I have defined the following structure below.
typedef union
{
struct
{
unsigned command:15;
unsigned acknowledge:1;
};
struct
{
unsigned short uicommand;
};
struct
{
Byte command_bytes[2];
};
}TCOMMAND;
After then declaring a variable of type TCOMMAND E.G
TCOMMAND mycommand
int x=sizeof(mycommand)
The value of x is 4 bytes instead of 2.
Enlightenment on the problem will be appreciated.
Thanks in advance.
In C/C++
unsignedmeansunsigned intand even if you don’t assign all of the bits of a bit field, the compiler will still size your structure to the data type specified.So assuming a 32 bit
int(which is the default in Visual C++) the first structure of your union is the same as:Which is four bytes. Use an
unsigned shortin your first structure if you want it to be only two bytes: