0

For this structure,

typedef struct division {
  bool b;
  union {
    uint16_t i;
    struct {
      uint8_t j;
      uint8_t k;
    };
  };
} type_t;

Why is the sizeof 4 and not 3? As I understand, the bool takes 1 byte. Then the union is allocated with the largest member's size. Since both the struct and the uint16_t are 16 bytes, the union should be 2 bytes. Then 2+1 would be 3. Where is the additional byte coming from?

  • Why is this post closed? I read that link before and still could not understand –  Mar 30 '20 at 17:48
  • Is there anything you need clarification for? It think the duplicate answers your question perfectly. – iz_ Mar 30 '20 at 17:49
  • Unless packed, `uint16_t` is not going to be on an odd address. – Weather Vane Mar 30 '20 at 17:49
  • follow the link. your misunderstanding have much more people and they have asked this question hundreds of times. – 0___________ Mar 30 '20 at 17:49
  • The answer is in the question of which this is a duplicate. The `uint16_t` type needs to be aligned on a multiple of 2 bytes, so the overall size of the structure must be a multiple of 2 bytes, and 3 is not a multiple of 2. There's probably a padding byte between `b` and the anonymous union. – Jonathan Leffler Mar 30 '20 at 17:50
  • There are many links to more information in the duplicate. It is hard to imagine there is something that has not been covered in every way possible. One answer has some nice diagrams.. – Weather Vane Mar 30 '20 at 17:52
  • Is it possible to use that padded space and 'overflow' the bool? –  Mar 30 '20 at 18:11

0 Answers0