struct S1
{
char c;
int i;
};
问sizeof(s1)等于多少?
 
聪明的你开始思考了,char占1个字节,int占4个字节,那么
加起来就应该是5。是这样吗你在你机器上试过了吗也许你是对的,但很可能你是错
的!VC6中按默认设置得到的结果为8。
Why为什么受伤的总是我
请不要沮丧,我们来好好琢磨一下sizeof的定义——sizeof的结果等于对象或者类型所
占的内存字节数,好吧,那就让我们来看看S1的内存分配情况:
S1 s1 = { 'a', 0xFFFFFFFF };
定义上面的变量后,加上断点,运行程序,观察s1所在的内存,你发现了什么
以我的VC6.0为例,s1的地址为0x0012FF78,其数据内容如下:
0012FF78: 61 CC CC CC FF FF FF FF
发现了什么怎么中间夹杂了3个字节的CC看看MSDN上的说明:
When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment.
原来如此,这就是传说中的字节对齐啊!一个重要的话题出现了。
struct PDU_7{
    unsigned char pdu_id; 
    unsigned char jack_id;
    unsigned char gun_id;
    int bullet;
    int lenght;
};
 
 
struct PDU_7{
    unsigned char pdu_id; 
    int lenght;
    unsigned char jack_id;
    unsigned char gun_id;
    int bullet;
    };
 
 这两种定义方法一样吗?
 
切忌:使用sizeof 时一定要记住进行调试

相关文章:

  • 2022-02-08
  • 2022-02-06
  • 2022-01-15
  • 2022-01-15
  • 2021-08-08
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
猜你喜欢
  • 2021-11-13
  • 2021-08-03
  • 2021-10-10
  • 2022-12-23
  • 2021-10-27
  • 2021-06-28
  • 2021-11-23
相关资源
相似解决方案