-1

I have VC++ 2012 and noticed that if have something like

struct mystruct{
     char a[100];
     __int64 b; };

then sizeof(mystruct) would yield 112.

Why is this?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 5
    Padding for alignment purposes. – Oliver Charlesworth Feb 16 '15 at 22:15
  • I need to get rid of it, because I'm writing the struct into a binary file – kalkanistovinko Feb 16 '15 at 22:16
  • 1
    That's a non-sequiter. How the `struct` is stored internally has no effect on how you serialize it for storage to a file. – David Schwartz Feb 16 '15 at 22:17
  • If you want to directly write the structure to a file (which *isn't* necessary, as @DavidSchwartz pointed out, and opens the door to endianity troubles and other possible problems that need addressing) you can probably employ `pragma pack` or its VC++ equivalent. – LSerni Feb 16 '15 at 22:20
  • 1
    So you have a binary file format that stores 8-byte integers *not* aligned on 8-byte boundaries? Where is this format specified? – Keith Thompson Feb 16 '15 at 22:20
  • 3
    Reverse the member order. But along with others I strongly discourage the blast-o-binary approach to writing this stuff to disk file. – WhozCraig Feb 16 '15 at 22:21

2 Answers2

1

Padding has to be added. Consider:

mystruct *a = (mystrct *) malloc (16 * sizeof (mystruct));

If there was no padding, some of the 64-bit integers wouldn't be aligned.

If you need data in a particular binary format, you must write code to put that data in that binary format. Don't try to do it by accident or by magic. Write code that produces precisely the bytes you want in the file.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

Why is this? Short answer, memory alignment.

The long answer is here: http://www.catb.org/esr/structure-packing/

Rob K
  • 8,757
  • 2
  • 32
  • 36