免费注册 查看新帖 |

Chinaunix

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

搞不清一个问题。。大虾进! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-03-15 11:00 |只看该作者 |倒序浏览
struct struct_size
{
       
        char b;
                int a;
        char c;
       
};
struct_size A;
cout<<sizeof(A); //此处输出结果为12;
struct struct_size
{
         int a;

        char b;
                       char c;
       
};//或把int a 移到int c 的后面,输出结果为:8(编译环境为.net2003)
这是为什么呢?谢谢。。。

此问题已经找到答案。。:http://www.linuxforum.net/forum/ ... mp;o=all&fpart=

[ 本帖最后由 ianglm 于 2006-3-16 10:01 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2006-03-15 11:40 |只看该作者
it is related to memory alignment, the purpose of which is to facilate memory access.
variables of int type should be stored in an address which can be divided by 4.
variables of char type have no alignment requirement.

struct {
        char        b;
        int        a;
        char        c;
}
is stored as
        *???        /* b */
        ****        /* a */
        *???        /* c */
here, "*" represents an occupied byte, "?" an unoccupied byte.

struct {
        int        a;
        char        b;
        char        c;
}
is stored as
        ****        /* a */
        **??        /* b c */

论坛徽章:
0
3 [报告]
发表于 2006-03-15 11:46 |只看该作者
这个问题是不是在不同编译器上也会有不同结果呢????

论坛徽章:
0
4 [报告]
发表于 2006-03-15 11:49 |只看该作者
参《C++程序设计语言》 5.7节中,
关于“对齐”、“空洞”的内容。



另:
蛱jiá
蝴蝶的一类,前足短小,触角锤状,成虫赤黄色,对农作物有害

论坛徽章:
0
5 [报告]
发表于 2006-03-15 13:07 |只看该作者
字节对齐问题

论坛徽章:
0
6 [报告]
发表于 2006-03-15 14:03 |只看该作者
原帖由 westgarden 于 2006-3-15 11:49 发表
参《C++程序设计语言》 5.7节中,
关于“对齐”、“空洞”的内容。



另:
蛱jiá
蝴蝶的一类,前足短小,触角锤状,成虫赤黄色,对农作物有害


不好意思。。把虾和蛱给弄错了。。。看来现在真的要好好的学学语文了:)

论坛徽章:
0
7 [报告]
发表于 2006-03-15 14:09 |只看该作者
原帖由 aldebran 于 2006-3-15 11:40 发表
it is related to memory alignment, the purpose of which is to facilate memory access.
variables of int type should be stored in an address which can be divided by 4.
variables of char type have n ...



As what you have told me .I have another question to ask you :

There is another struct:
  sturct struct_size{
   char a;
   char b;
}
what is the result sizeof(struct_size)?

论坛徽章:
0
8 [报告]
发表于 2006-03-15 16:42 |只看该作者

  1. There is another struct:
  2.   sturct struct_size{
  3.    char a;
  4.    char b;
  5. }
  6. what is the result sizeof(struct_size)?
复制代码

结果当然为2

论坛徽章:
0
9 [报告]
发表于 2006-03-15 16:48 |只看该作者
原帖由 aldebran 于 2006-3-15 11:40 发表
it is related to memory alignment, the purpose of which is to facilate memory access.
variables of int type should be stored in an address which can be divided by 4.
variables of char type have n ...


有趣
受教!
谢谢

论坛徽章:
0
10 [报告]
发表于 2006-03-15 17:45 |只看该作者
字节对齐问题啊。 赫赫
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP