Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

c - Size of struct containing double field

Firstly, I understand byte padding in structs. But I have still a small test contain a double field in struct and I don't know how to explain this :

typedef struct {
    char a;
    double b;
}data;

typedef struct{
    char a;
    int b;
}single;

int main(){
    printf("%d
",sizeof(double));
    printf("%d
",sizeof(single));
    printf("%d
",sizeof(data));
}

Through out this test, the answer is : 8 8 and 16.

Why this result make me thinking ?

By second test, we can see size of word on my machine is 4 bytes.

By first test, we can see size of double is 8 bytes.

So, at the struct data : the result should be 12 bytes : 4 bytes for char and 8 bytes for double.

But, I don't know why the result is 16 bytes. (So strange with me)

Please explain it for me, thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's sixteen bytes so that if you have an array of datas, the double values can all be aligned on 8-byte boundaries. Aligning data properly in memory can make a big difference in performance. Misaligned data can be slower to operate on, and slower to fetch and store.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...