为什么记录的大小不等于其字段的大小之和? [英] Why isn't the size of a record equal to the sum of the sizes of its fields?

查看:86
本文介绍了为什么记录的大小不等于其字段的大小之和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码:

type TRecord1 = record
  myarr: array [0..31] of single:
end;
type TRecord2 = record
  b1, b2, b3, b4, b5, b6: byte;
end;
type TRecord3 = record
  myarr: array [0..31] of single:    
  b1, b2, b3, b4, b5, b6: byte;
end;

procedure TForm1.FormCreate(Sender: Tobject);
begin
  ShowMessage(IntToStr(SizeOf(TRecord1))+'+'+IntToStr(SizeOf(TRecord2))+
      '='+IntToStr(SizeOf(TRecord3)));
end;

程序显示以下消息:

128+6=136

为什么是 SizeOf(TRecord3)等于136而不是134?

Why is SizeOf(TRecord3) equal to 136 rather than 134?

推荐答案

这是由于填充由于记录对齐而添加。 TRecord3 的对齐方式为4,因为它包含单个值。因此,在记录的末尾添加了填充以使大小精确地为4的倍数。这就是为什么大小为136而不是您期望的值134的原因。

This is due to padding added because of record alignment. TRecord3 has alignment of 4 since it contains single values. And so padding is added to the end of the record to make the size an exact multiple of 4. That's why the size is 136 rather than the value of 134 that you were expecting.

您可以声明记录被打包为 ,或者等效地,将对齐编译器选项设置为 $ ALIGN 1 。对齐方式为 1 时,不会在记录中添加填充,并且 SizeOf(TRecord3)= 134 。但是,我强烈建议您不要这样做。使用自然对齐方式可以最有效地访问记录。例如,处理器加载未对齐的值比加载对齐的值更昂贵。对于整数,自然对齐方式为4字节边界。对于 double ,自然对齐方式为8字节边界,依此类推。如果需要与另一个使用打包记录的库进行二进制兼容性,则应该使用打包记录。

You can declare your record to be packed, or, equivalently, set the alignment compiler option to $ALIGN 1. With an alignment of 1 there will be no padding added to the record and SizeOf(TRecord3)=134. However, I strongly recommend you do not do this. Using the natural alignment results in the most efficient memory access for records. For example, it is more expensive for the processor to load a misaligned value than to load an aligned value. For a single or an integer, the natural alignment is on a 4 byte bounday. For a double the natural alignment is on an 8 byte boundary and so on. You should use packed records if you need binary compatibility with another library that uses packed records.

这篇关于为什么记录的大小不等于其字段的大小之和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆