Sizeof Reports Improper Size of Type-defined Structure - C++
My application has a defined structure:
typedef struct zsSysVersionMsg_tag
{
WORD cmd;
BYTE len;
} zsSysVersionMsg_t;
I would expect sizeof(z开发者_开发问答sSysVersionMsg_t)
to evaluate to 3. However, when I run my application it evaluates to 4. Can someone explain why this is? (I really need it to evaluate to 3.) Thanks.
Most platforms will "align" and "pad" structures so that they begin and end exactly on a word boundary. This is done to improve memory performance.
Assuming you are on Windows, you can set your own alignment. In your case, you want to align on single bytes, so do this:
#pragma pack( push, 1 )
typedef struct zsSysVersionMsg_tag
{
WORD cmd;
BYTE len;
} zsSysVersionMsg_t;
#pragma pack( pop )
精彩评论