以文本方式查看主题

-  曙海教育集团论坛  (http://peixun0.cn/bbs/index.asp)
--  C语言开发  (http://peixun0.cn/bbs/list.asp?boardid=62)
----  各位对C语言结构中成员的对齐(alignment)怎样理解?  (http://peixun0.cn/bbs/dispbbs.asp?boardid=62&id=2412)

--  作者:wangxinxin
--  发布时间:2010-12-10 11:47:29
--  各位对C语言结构中成员的对齐(alignment)怎样理解?
本来觉得自已很清楚了,后来看到一个例子,又糊涂了。先看一个WATCOM给出的表:(ZP1表示按一个字符对齐) zp1 zp2 zp4 zp8 zp16 sizeof(member) \\--------------------------------------- 1 | 0 0 0 0 0 2 | 0 2 2 2 2 4 | 0 2 4 4 4 8 | 0 2 4 8 8 16 | 0 2 4 8 16 x | aligned to largest member 看一段代码: #include #include typedef struct memo_el { char date[9]; struct memo_el *prev,*next; int ref_number; char sex; } memo; main( ) { printf( "Offset of %s is %d\\n", "date", offsetof( memo, date ) ); printf( "Offset of %s is %d\\n", "prev", offsetof( memo, prev ) ); printf( "Offset of %s is %d\\n", "next", offsetof( memo, next ) ); printf( "Offset of %s is %d\\n", "ref_number", offsetof( memo, ref_number ) ); printf( "Offset of %s is %d\\n", "sex", offsetof( memo, sex ) ); printf( "Size of %s is %d\\n", "memo", sizeof( memo ) ); printf( "Number of padding bytes is %d\\n", sizeof( memo ) - (offsetof( memo, sex ) + sizeof( char )) ); return 0; } 输出: 16位zp1:(毫无疑问) Offset of date is 0 Offset of prev is 9 Offset of next is 11 Offset of ref_number is 13 Offset of sex is 15 Size of memo is 16 Number of padding bytes is 0 16位 zp2、4、8结果都一样: Offset of date is 0 Offset of prev is 10 Offset of next is 12 Offset of ref_number is 14 Offset of sex is 16 Size of memo is 18 Number of padding bytes is 1 如果再把成员改一个长整类型, typedef struct memo_el { char date[9]; struct memo_el *prev,*next; long int ref_number; char sex; } memo; 结果在16位ZP2-8都是这样: Offset of date is 0 Offset of prev is 10 Offset of next is 12 Offset of ref_number is 16 Offset of sex is 20 Size of memo is 24 Number of padding bytes is 3 现在我无法解释了~