the struct size

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;
struct s
{
    int *a,b;
    char c;
};
int main()
{
    s s1;
    cout << sizeof(s1) << endl;
    return 0;
}


why the answer is 12 not 9
Because the answer is 12 and not 9. It is likely padded for alignment purposes.
It is likely padded for alignment purposes.


thank you for your reply
It is likely padded for alignment purposes.

I feel confused.
Sounds like your platform uses 32 bit ints and 32 bit pointers.
That means the layout of your object is: 4 bytes a, 4 bytes b, 1 byte c, 3 bytes padding.
Without trailing padding, if you would make an array of two such objects, the second object's member a would not be at an address that's divisible by four, violating int's alignment requirement.
if the code is
1
2
3
4
5
6
struct a
 {
    int *a;
    double b;
    char c;
};

the answer should be 16,shouldn't it?
maybe the answer is also depend on the complier,the codeblocks say it is 24
it runs on the codepad.org(the online complier),the answer is 16.
Last edited on
It's 24 (8 + 8 + 1 + 7) in typical 64-bit environment, and 16 (4 + 8 + 1 + 3) in typical 32-bit environment.
Last edited on
I think that the codeblocks has integers of size 8. As for codepad.org then it is possible that some compiler option is used that sets the default alignment to the paragraph boundary.
Last edited on
Topic archived. No new replies allowed.