sizeof gives wrong results?

Hello, I have a question about sizeof() operator"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct s1
{
short y;
int *p;
};

int main()
{

cout <<"size of ss1::y : "<<sizeof(s1::y)<<endl; // 2 bytes
cout <<"size of ss1::p : "<<sizeof(s1::p)<<endl; // 4 bytes
cout <<"size of struct : "<<sizeof(s1)<<endl;     // 2+4=8bytes?

}

Why sizeof(s1) is 8 bytes? Shouldn't it be 6 bytes?
Thanks for help.
padding.

structs are often padded to DWORD sizes to make indexing more efficient.
Are these padding bytes placed at the beginning or at the end of structure?
At the end.
No, they are placed anywhere the compiler feels like putting them.

Most likely in your case the bytes are between y and p so that p is word-aligned.

That nice to know.

tried many other: i'm using gcc .
1
2
3
4
5
struct s1
{
    char x;
    int i;
};

size = 8
1
2
3
4
5
6
struct s2
{
    char x;
    int i;
    char z;
};

size = 12
1
2
3
4
5
6
struct s3
{
    char x;
    char z;
    int i;
};

size = 8
Because the compiler have to make sure, that the integer var lies on an address that is a multiple of 4 (32bit) or something like this.
While you're at it, note that an empty class has a size of [at least] 1.
All compilers provide a #pragma to change the alignment.
Thanks.
Topic archived. No new replies allowed.