加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 我在这个K&R样本中缺少什么?

发布时间:2020-12-16 09:33:32 所属栏目:百科 来源:网络整理
导读:以下是K R的The C Programming Language(第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
以下是K& R的The C Programming Language(第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.

因此,据我所知,其目的是确保标头实例占用sizeof(Align)倍数的字节数.这个目标对我来说非常有意义.

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

在这种情况下,我认为有必要将Align定义为其他东西(也许是双倍).但是我不太确定我是否完全理解什么会决定某个特定架构的选择.它只是“最大”类型吗?如果长期是最大的类型 – 它不能以我上面描述的方式工作吗?

谢谢

解决方法

编译器将调整标头的大小,以便可以从header []数组中的元素有效地检索ptr,size和x.在大多数体系结构中,x的存在意味着sizeof(header)将增加到sizeof(long)的倍数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读