0
#include <stdint.h>
#include <stdio.h>

typedef struct {
  uint8_t d;
  uint8_t data[2];
} struct1;

typedef struct {
  uint16_t a;
  uint8_t d;
  uint8_t data[2];
} struct2;

int main(void) {
  printf("%u\n", sizeof(struct1));
  printf("%u\n", sizeof(struct2));
  return 0;
}

I would expect struct1 to have a size of 3, and struct2 to have a size of 5. However when I run this code, I see that struct2 has a size of 6.

>./main
3
6

I guess the compiler is doing some sort of padding here, but why is struct 1 allowed to have an odd byte size but not struct 2?

Peter Kapteyn
  • 354
  • 1
  • 13

0 Answers0