免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2337 | 回复: 6
打印 上一主题 下一主题

一个c语言对齐的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-10-31 22:54 |只看该作者 |倒序浏览
  1. struct test
  2. {
  3.     char c;
  4.     double d;
  5.     int t;
  6. };
复制代码
请问这个结构体的sizeof为什么是16, 对齐的不应该是char 和double之前填充7个字节 , 为什么不是20

论坛徽章:
0
2 [报告]
发表于 2010-11-01 10:32 |只看该作者
你的编译器 默认 4字节对齐
char c      4
double d  8
int t         4

论坛徽章:
0
3 [报告]
发表于 2010-11-01 10:59 |只看该作者
我用VC和gcc试的,结果是24。楼主的编译器可能有默认对其,或者优化。
按理说应该是按照结构体中成员最大的size对其,此例中就是8

论坛徽章:
0
4 [报告]
发表于 2010-11-01 17:16 |只看该作者
我也用gcc编译、测试出来的结果是16。

我的gcc的版本信息:
$ gcc -v
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-1.4.2.0/jre --with-cpu=generic --host=i386-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-44)

论坛徽章:
0
5 [报告]
发表于 2010-11-01 18:26 |只看该作者
我就是用gcc试的  请问3l怎么看编译器的默认对齐值  我在编译的时候没有做任何优化

论坛徽章:
0
6 [报告]
发表于 2010-11-01 19:08 |只看该作者
看到一种说法:
在vc6中基本类型的数据对齐在sizeof(基本类型的数据)上(以下说"对齐在N上"的意思就是:地址%N=0)
在gcc中char对齐在1上,short对齐在2上,int对齐在4上,double对齐在4上。</a>

论坛徽章:
0
7 [报告]
发表于 2010-11-01 19:24 |只看该作者
*  A char (one byte) will be 1-byte aligned.
    * A short (two bytes) will be 2-byte aligned.
    * An int (four bytes) will be 4-byte aligned.
    * A float (four bytes) will be 4-byte aligned.
    * A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux (8-byte with -malign-double compile time option).
    * A long double (twelve bytes) will be 4-byte aligned on Linux.
    * Any pointer (four bytes) will be 4-byte aligned on Linux. (e.g.: char*, int*)
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP