我从这个 K&R 样本中遗漏了什么? [英] What am I missing from this K&R sample?

查看:64
本文介绍了我从这个 K&R 样本中遗漏了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下摘自 K&R 的 The C Programming Language(第 8.7 节)中的代码示例:

The following is an excerpt from a code sample in K&R's The C Programming Language (section 8.7):

typedef long Align;

union header {
    struct {
        union header *ptr;
        unsigned size;
    } s;
    Align x;
};

typedef union header Header;

这里是解释性摘录:

为了简化对齐,所有块都是标头大小的倍数,以及标头正确对齐.这是由包含所需的标题结构和最严格的类型的实例,这是我们随意制作的.

To simplify alignment, all blocks are multiples of the header size, and the header is aligned properly. This is achieved by a union that contains the desired header structure and an instance of the most restrictive type, which we have arbitrarily made a long.

所以,据我所知,这个想法是确保 header 实例占用的字节数是 sizeof(Align) 的倍数.这个目标对我来说很有意义.

So, as I understand it, the idea is to ensure that a header instance takes up a number of bytes that is a multiple of sizeof(Align). The goal makes perfect sense to me.

但是考虑long为64位,int为32位,指针为64位的情况.在这种情况下,header.s 将是 64+32 = 96 位.因此,sizeof(header) 将是 96 位,这不是预期的 64 的倍数.

But consider the case where long is 64 bits, int is 32 bits, and a pointer is 64 bits. In that case, header.s will be 64+32 = 96 bits. Thus, sizeof(header) will be 96 bits, which is not a multiple of 64 as intended.

在这种情况下,我认为有必要将 Align 定义为其他东西(可能是 double).但我不太确定我是否完全理解是什么决定了特定架构的选择.它只是最大"的类型吗?如果 long 是最大的类型怎么办 - 它不能以我上面描述的方式工作吗?

In such a case, I suppose it would be necessary to define Align as something else (perhaps double). But I'm not quite sure whether I'm fully understanding what would dictate that choice for a particular architecture. Is it just the "biggest" type? And what if long is the biggest type - couldn't it fail to work in the way I described above?

谢谢

推荐答案

编译器会调整header的大小,使得ptr,size> 和 x 都可以从 header[] 数组中的元素有效地检索.在大多数架构上,x 的存在意味着 sizeof(header) 将增加到 sizeof(long) 的倍数.

The compiler will adjust the size of header so that ptr, size, and x can all be retrieved efficiently from elements in a header[] array. On most architectures, the presence of x means that sizeof(header) will be increased to a multiple of sizeof(long).

这篇关于我从这个 K&R 样本中遗漏了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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