Explain why sizeof(char) and sizeof(int) returns 8

The below code outputs "8". char+int=5 bytes, not 8. Where are the other 3 bytes coming from?
1
2
3
4
5
6
7
8
9
10
struct myStruct
{
   char a;   // char = 1 byte
   int  b;   // int = 4 bytes
};

int main()
{
    cout << sizeof(myStruct) << endl;
}
closed account (1vRz3TCk)
Padding. I can't remember the exact details but the struct will be 4 (?) byte aligned. So the compiler will pack the items into four byte chunks, the int fits into one chunk and the char along with 3 bytes of padding fits into the other.

Edit:
it is worth keeping an eye on the order you declare elements as well:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct struct_A
{
   char a;   // char = 1 byte
   int  b;   // int = 4 bytes
};

struct struct_B
{
   char a;   // char = 1 byte
   char c;
   int  b;   // int = 4 bytes
};

struct struct_C
{
   char a;   // char = 1 byte
   int  b;   // int = 4 bytes
   char c;
};

int main()
{
    std::cout << sizeof(struct_A) << std::endl;
    std::cout << sizeof(struct_B) << std::endl;
    std::cout << sizeof(struct_C) << std::endl;

    return 0;
}


8
8
12
Last edited on
If you hate the padding, try #pragma pack(1).
But beware that the alignment can matter with some computer architectures; with Intel it just has a performance impact, but on some architectures (e.g. ARM) it can cause memory alignment violations.

In general you should use default packing for a given architecture unless you have good reason not to.

One reason is large arrays. But with the memory available to modern computers this is much less an issue than it used to be.
It's also worth mentioning that none of this should matter in any program you write. You shouldn't write code assuming data is stored a certain way
The technique is often used when overlaying a struct onto a byte buffer that contains some binary protocol.
Topic archived. No new replies allowed.