首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于struct大小的判断解决方法

2012-04-21 
关于struct大小的判断在程序里面我们可以用sizeof判断额下面这个struct:struct Motionevent{unsigned int

关于struct大小的判断
在程序里面我们可以用sizeof判断额
下面这个struct:

struct Motionevent
{
unsigned int x;
unsigned int y;
} ;
struct Buttonevent
{
unsigned char button;
unsigned char press ;
} ;
struct Keyevent
{
unsigned int key;
unsigned char press ;
} ;
struct Event
{
unsigned char type;
union
{
struct Motionevent moteev;
struct Keyevent keyev;
struct Buttonevent buttonev;
} u;
};
假定,Size of unsigned int 4,Size of unsigned char 1

那么这个struct Event的大小不应该是1+4+4+4+4+1+1么?不应该是19么?因为内部对齐什么的,但是我sizeof的结果是12
就算不管内部对齐什么的,全部加上最少也是16啊,麻烦哪位大神说下这个是怎么算的啊?

[解决办法]
union联合体的大小是里面占内存最大的变量的大小!
[解决办法]
应该是 1+4+4,然后内存对齐的原因,12.
了解下 union的知识和对齐.
[解决办法]
int type 是4个,union是4个(以占内存最大的变量为标准)所以4 + 4 = 8

探讨

同样的,在这个例子里s的大小
struct us
{
int type;
union
{
int x;
float y;
char z;
} u;
};
struct us s;

Size of int: 4 bytes
Size of float: 4 bytes
Size of char: 1 byte
为什么电脑sizeof s的答案是8呢?,我电脑里i……

[解决办法]
按照4字节对齐来就行了
[解决办法]
此时联合体的大小就是里面占字节最大的变量的字节,就是8个字节了,但是struct不是以8个字节 对齐,要把此时那个最大字节的结构体的成员变量和外面的那个结构体里面的成员变量再进去内存字节对齐
探讨

不对- -|||
如果按我的理解,那第一个就应该是8翻一倍,大小是16了……
我去翻翻书再好好理解下struct的对齐方式吧……
按照4字节来对齐?对所有的平台都是这样么?

[解决办法]
union
{
struct Motionevent moteev;
struct Keyevent keyev;
struct Buttonevent buttonev;
} u;

的size是其中最大元素的size,而不是3个struct加起来的大小。很显然Motionevent的最大,是8bytes,因此
sizeof(u) = 8

struct Event
{
unsigned char type; // 1byte, + 3bytes padding
// 8bytes
};

所以sizeof(struct Event) = 12bytes

热点排行