Reputation: 553
I got the following struct:
struct Packet
{
short PacketSize;
short Type;
};
struct SizeValidity
{
short SizeEnc;
};
struct SendEncSecureCode
{
Packet header;
short EncSecurityToken;
int lTime;
SizeValidity ending;
};
And on my code i want to get the size of the struct with the sizeof operator like this:
SendEncSecureCode sendpacket;
sendpacket.header.PacketSize = sizeof SendEncSecureCode;
Problem is i always get size 0x10 instead of 0x0C i am specting, so i change the INT type to DWORD and still the same problem, later i try with DWORD32 and still the same, the compiler is setting it as 8 bytes. I am working on VC11 Beta and the soft is aim to x86 not x64. Thanks
Upvotes: 1
Views: 124
Reputation: 29529
This is called padding. The compiler pads the space between the different members of the structure with zero bytes to better-align the members to addresses that can be read quicker by the CPU. You can (but should not unless you have a very good reason) override this behavior with the pack
pragma:
#pragma pack(push, 0)
struct {...};
#pragma pack(pop)
This forces the padding for this struct to be zero bytes. You can change the zero around.
Upvotes: 3
Reputation: 3582
To get the size you're expecting, you can tell the compiler to use 1-byte packing:
#pragma pack(push, 1)
struct Packet
{
short PacketSize;
short Type;
};
struct SizeValidity
{
short SizeEnc;
};
struct SendEncSecureCode
{
Packet header;
short EncSecurityToken;
int lTime;
SizeValidity ending;
};
#pragma pack(pop)
Please see http://vcfaq.mvps.org/lang/11.htm
Upvotes: 0