曙海教育集团论坛开发语言培训专区C语言开发 → 各位对C语言结构中成员的对齐(alignment)怎样理解?


  共有7267人关注过本帖树形打印

主题:各位对C语言结构中成员的对齐(alignment)怎样理解?

美女呀,离线,留言给我吧!
wangxinxin
  1楼 个性首页 | 博客 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:青蜂侠 帖子:1393 积分:14038 威望:0 精华:0 注册:2010-11-12 11:08:23
各位对C语言结构中成员的对齐(alignment)怎样理解?  发帖心情 Post By:2010-12-10 11:47:29

本来觉得自已很清楚了,后来看到一个例子,又糊涂了。先看一个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 现在我无法解释了~

支持(0中立(0反对(0单帖管理 | 引用 | 回复 回到顶部

返回版面帖子列表

各位对C语言结构中成员的对齐(alignment)怎样理解?








签名