您的位置:首页 > 其它

struct和union的大小问题

2011-11-08 17:25 344 查看

union类型以其中size最大的为其大小

struct类型以其中所有size大小之和为其大小


#include<iostream>


using namespace std;




int main()


{


typedef union {long i; int k[5]; char c;} DATE;


struct data { int cat; DATE cow; double dog;} too;


DATE max;




cout<<"sizeof(struct date)+sizeof(max) = "<<sizeof(too)+sizeof(max)<<endl;


cout<<"sizeof(too) = "<<sizeof(too)<<endl;


cout<<"sizeof(max) = "<<sizeof(max)<<endl;


cout<<"struct data.cow size = "<<sizeof(too.cow)<<endl;


cout<<"union DATE.i size = "<<sizeof(max.i)<<endl;


cout<<"union char.c size = "<<sizeof(max.c)<<endl;




}
sizeof(struct date)+sizeof(max)返回52


#include<iostream>


using namespace std;




int main()


{


typedef union student


{


char name[10];


long sno;


char sex;


float score [4];


} STU;




STU a[5];




cout<<sizeof(a)<<endl;




return 0;




}
初始化了一个含有5个UNION的数组,由于UNION以其中最大的元素float作为大小 16*5=80


#include<iostream>


using namespace std;




int main()


{


typedef struct student


{


char name[10];


long sno;


char sex;


float score [4];


} STU;




STU a[5];




cout<<sizeof(a)<<endl;




return 0;




}
输出为180

自然对齐(natural alignment)即默认对齐方式,是指按结构体的成员中(类型)size最大的成员作为基本的分配单元,而且与其顺序有这密切的联系。size最大的是long,size是 4,所以,按照顺序,Char name[10];12个字节;Long sno; 4个字节;Char sex; 4个字节(这里对齐了);Float score [4]; 16个字节。于是(12+4+4+16)×5=180


#include<iostream>


using namespace std;




int main()


{


typedef struct student


{


char name[10];


char sex;


long sno;


float score [4];


} STU;




STU a[5];




cout<<sizeof(a)<<endl;




return 0;




}
答案是:160. 为什么,只是换了顺序而已呀?关键就在顺序上。
结构体中,size最大的是long,size是 4,所以,按照顺序,Char name[10];12个字节;但是这12中多分配的2个字节可以包含后面的Char sex; (问题就在这);Float score [4]; 16个字节。于是(12+4+16)×5=160
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: