0

I have a data structure like this:

struct mystruct
{
    float f;
    int16_t i;
};

sizeof(int16_t) gives 2, but sizeof(mystruct) gives 8 instead of 6. Why is that? How can I declare an int16_t variable of 2 bytes inside my data structure?

Jacky Lee
  • 1,193
  • 3
  • 13
  • 22

1 Answers1

2

That is because of padding, given your system's architecture, the compiler adds some space to the structure.

If you try to add another int16_t, you'll see that the size of this structure will still be 8.

struct mystruct
{
    float f;
    std::int16_t i;
    std::int16_t g;
};

In your original case

struct mystruct
{
    float f;
    std::int16_t i;
    //2 bytes padding
};

Note also that you can have padding in between members in the structure, that is why it is usually good advice to sort the members by decreasing order size, to minimize padding.

You can have a quick read at the corresponding wikipedia page, which is well written. http://en.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86

dau_sama
  • 4,247
  • 2
  • 23
  • 30
  • To see this online: https://ideone.com/VPIcCx Also, notice what happens when we rearrange the order: https://ideone.com/oexV51 – simon Jun 03 '15 at 08:09
  • this last rearrangement should help him understand better! thanks for the ideone! – dau_sama Jun 03 '15 at 08:13