-1

There is a problem with msvc. I make a struct example.

struct example
{
char a[1];
short b;
}

when you look at this struct, it's size looks like 3 byte but when it is odd size, msvc add one more byte to make it even size.

I want it 3 byte size. How can I do it?

visual stuido 2022 c++14 msvc.

I tried other variable types and still not odd size.

  • IT's called padding. The `short b` needs to start on a address that is divisible by 2. There are pragmas for disabling padding at the expense of less optimal runtime performance. – selbie Sep 02 '23 at 18:03
  • https://stackoverflow.com/questions/8933707/locally-disable-padding – selbie Sep 02 '23 at 18:04
  • https://learn.microsoft.com/en-us/cpp/cpp/align-cpp?view=msvc-170 – selbie Sep 02 '23 at 18:06
  • tldr: you probably want `__declspec(align(1))` – selbie Sep 02 '23 at 18:06
  • *I tried other variable types and still not odd size.* Did you try `struct example { char a[1]; char b[2]; };`? – Eljay Sep 02 '23 at 18:18
  • Yes I tried. not work – MORETHANYOU Sep 02 '23 at 18:19
  • Switch the order. Place the `short` type first, followed by the `char` variable. The compiler doesn't *need* to add padding after the `short`, because `char` can start on any boundary. The compiler *may* add padding for the next variable instance. – Thomas Matthews Sep 02 '23 at 18:39

0 Answers0