联合内部结构的填充如何工作? [英] How does padding of structs inside unions work?

查看:65
本文介绍了联合内部结构的填充如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

#include <stdio.h>

typedef union u_data
{
        struct
        {
                int a;
                int b;
                int c;
        };
                int elem[3];
}       my_data;

int     main(void)
{
        my_data data;

        data.a = 3;
        data.b = 5;
        data.c = -3;
        printf("%d, %d, %d\n", data.elem[0], data.elem[1], data.elem[2]);
}

它按我的预期工作,输出:3, 5, -3

and it works as I expected with output: 3, 5, -3

但是我知道结构体可以有填充,这是否意味着结构体中的元素可能并不总是与数组对齐?

however I understand that structs can have padding in them so does that mean that the elements in the struct might not always align with the array?

推荐答案

  • 首先,C、C11 6.5.2.3 中的联合有一个特殊的规则公共初始序列":

    • First of all, there is a special rule "common initial sequence" for unions in C, C11 6.5.2.3:

      为了简化联合的使用,做了一个特殊的保证:如果联合包含几个结构共享一个共同的初始序列(见下文),如果联合对象当前包含这些结构之一,允许检查公共任何地方的任何地方的初始部分,即联合的完整类型的声明可见.

      One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible.

      这个规则在这里并不适用,因为你的情况是一个结构体和一个数组.如果是两个结构体,就会应用该规则.

      This rule does not apply here though, since your case is a struct and an array. Had it been two structs, the rule would have applied.

      确实,结构体可能有填充,因此如果数组与结构体的对齐方式不同,则不能保证获得正确的输出.这是实现定义的行为.

      Indeed a struct may have padding, so you are not guaranteed to get the correct output if the array is aligned differently than the struct. This is implementation-defined behavior.

      写入结构体和读取数组是很好的,并且在 C(与 C++ 不同)、C11 6.5.2.3/3 中定义良好,因为这两种类型是兼容的.如果没有填充字节,则结构只能与数组兼容.

      Writing to the struct and reading from the array is fine and well-defined in C (unlike C++), C11 6.5.2.3/3, given that the two types are compatible. The struct can only be compatible with the array if there are no padding bytes.

      严格别名"在此处不适用.

      "Strict aliasing" does not apply here.

      总结:这是实现定义的行为.如果编译器保证它,您可以依赖某个系统上的某个行为.代码不可移植.

      Summary: this is implementation-defined behavior. You may rely on a certain behavior on a certain system, if the compiler guarantees it. The code will not be portable.

      这篇关于联合内部结构的填充如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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