2

I have a c++ structure:

struct a
{
     char b;
     int c;
     int d[100];
};

The size of the struct should be 405 bytes. I saw that the size of the struct is 408 bytes. The reason is the alignment to 8 bytes after the integer "c". The array "d" should start at the 6th byte of the struct and not at the 9th byte. I used #pragma pack(1) but it didn't solve the problem. I cannot change the order of fields in the struct. Do you have any idea how can I solve this problem? Thanks!

10
  • 3
    With which compiler? On which system? Why do you need this? Commented Mar 1, 2014 at 8:45
  • Visual studio's default compiler. Windows. I need to send this struct to a remote computer Commented Mar 1, 2014 at 8:49
  • The problem is that I send a bigger struct than the desired size Commented Mar 1, 2014 at 8:52
  • Here is a idea serialize it and take into account endianess. Then let it be free over the network
    – Ed Heal
    Commented Mar 1, 2014 at 9:06
  • 1
    Using gcc 4.8 or clang 3.5 sizeof(a) is 405 bytes - with pragma pack directive. Commented Mar 1, 2014 at 9:29

1 Answer 1

7

The fault packing for most compilers I use is that objects align on their own size. The default packing for your struct would insert padding after the char and before the first int, to place that int on a 4 byte boundary. Obviously this is the behaviour you are seeing.

The code I use on Visual Studio to achieve packing looks like this.

#pragma pack(push,1)
struct a {
  char b;
  int c;
  int d[100];
};
#pragma pack(pop)

It removes the padding, aligning the int on byte 1.

If I get some time I'll check it on a couple of versions of VS to confirm that, but my current code works exactly like this. This is how it's done, so the only question is why it isn't working for you.

EDIT: sizeof(a) is 405 as expected. Offset of b is 1. VS2012. Gcc is the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.