the struct size

Apr 2, 2013 at 8:35am
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
Apr 2, 2013 at 8:39am
Because the answer is 12 and not 9. It is likely padded for alignment purposes.
Apr 2, 2013 at 8:53am
It is likely padded for alignment purposes.


thank you for your reply
Apr 2, 2013 at 10:27am
It is likely padded for alignment purposes.

I feel confused.
Apr 2, 2013 at 11:58am
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.
Apr 2, 2013 at 1:28pm
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 Apr 2, 2013 at 1:31pm
Apr 2, 2013 at 1:47pm
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 Apr 2, 2013 at 1:50pm
Apr 2, 2013 at 1:48pm
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 Apr 2, 2013 at 1:48pm
Topic archived. No new replies allowed.