有什么好的例子可以说明结构体和联合体的区别吗? 基本上我知道struct使用了它成员的所有内存,而union使用了最大的成员内存空间。还有其他操作系统级别的差异吗?


当前回答

当我们需要对具有一组独立属性的事物进行建模时,建议使用结构;当一个实体具有多种形式且一次只能以一种形式存在时,建议使用联合。

让我们看看它们可以应用的两个地方

您需要存储和更新汽车的值。为了做到这一点,我们需要记录汽车的所有属性,如型号、里程、价格和燃料类型。这些值总是存在于一辆车中,它们不依赖于其他值。 因此,我们需要一种数据类型,它不仅存储所有属性,而且还确保它们的正确更新。这种类型的任务可以使用结构来完成。

struct car{
    char model[];
    int mileage;
    int price;
    char fuel_type[];
};

组织需要从大量客户那里收集您的数据以进行付款验证。现在,为了数据完整性和客户安全,一个组织被指示从一个人那里获得最少的详细信息。 这些详细信息可以是您的PAN号码或帐户号码或选民身份证。现在,因为我们需要收集这些细节中的任何一个,同时也要节省内存,我们可以在这里使用联合。它将只保存提供给它的单个值。

union verification_details{
    char account_number[10];
    char PAN[10];
    char voter_id[10];
};

我发现下面的文章解释得很好:结构和联合的区别

其他回答

在编写下面给出的字节排序函数时,联合非常方便。这在结构体中是不可能的。

int main(int argc, char **argv) {
    union {
        short   s;
        char    c[sizeof(short)];
    } un;

    un.s = 0x0102;

    if (sizeof(short) == 2) {
        if (un.c[0] == 1 && un.c[1] == 2)
            printf("big-endian\n");
        else if (un.c[0] == 2 && un.c[1] == 1)
            printf("little-endian\n");
        else
            printf("unknown\n");
    } else
        printf("sizeof(short) = %d\n", sizeof(short));

    exit(0);
}
// Program from Unix Network Programming Vol. 1 by Stevens.

从技术上讲,非指:

假设:椅子=记忆块,人=变量

结构:如果有3个人,他们可以坐在相应大小的椅子上。

工会:如果有3个人,只有一张椅子可以坐,所有人都需要在他们想坐的时候使用同一把椅子。

技术上讲是指:

下面提到的程序对结构和联合进行了深入研究。

struct MAIN_STRUCT
{
UINT64 bufferaddr;   
union {
    UINT32 data;
    struct INNER_STRUCT{
        UINT16 length;  
        UINT8 cso;  
        UINT8 cmd;  
           } flags;
     } data1;
};

MAIN_STRUCT size =sizeof(UINT64) for bufferaddr + sizeof(UNIT32) for union + 32 bit for padding(取决于处理器架构)= 128 bits。 对于结构,所有成员连续获取内存块。

Union获得一个最大大小成员的内存块(这里是32位)。 在联合内部还有一个结构体(INNER_STRUCT),它的成员获得一个总大小为32位(16+8+8)的内存块。在联合中,可以访问INNER_STRUCT(32位)成员或data(32位)。

有什么好的例子可以说明结构体和联合体的区别吗?

下面是来自嵌入式系统应用的真实例子。它只使用联合,但它清楚地显示了联合的功能。

I2C通信协议的写函数在从传递给它的数组中检索数据时使用联合类型,用于数据存储。

union data
{
    uint32_t packet;
    uint8_t  packetbyte[4];
} txdata;

通过指针传递给write函数的数组包含一个字节大小的元素。在for循环中,这些字节分四个步骤逐一提取,并存储到txdata的各个元素中。packetbyte成员。

循环结束后,txdata。数据包包含4个字节的数据,这些数据被连续存储到txdata联合中。作为通过通信总线发送数据的最后一步,txdata。数据包被写入32位缓冲区,在被写入后,32位缓冲区启动写序列。然后通过txdata重置内容。在next for循环开始执行之前,Packet = 0。

通过这种方式,I2C主机可以重新传输32位数据包,直到发送通过的输入数据并终止写入功能。

As you already state in your question, the main difference between union and struct is that union members overlay the memory of each other so that the sizeof of a union is the one , while struct members are laid out one after each other (with optional padding in between). Also an union is large enough to contain all its members, and have an alignment that fits all its members. So let's say int can only be stored at 2 byte addresses and is 2 bytes wide, and long can only be stored at 4 byte addresses and is 4 bytes long. The following union

union test {
    int a;
    long b;
}; 

could have a sizeof of 4, and an alignment requirement of 4. Both an union and a struct can have padding at the end, but not at their beginning. Writing to a struct changes only the value of the member written to. Writing to a member of an union will render the value of all other members invalid. You cannot access them if you haven't written to them before, otherwise the behavior is undefined. GCC provides as an extension that you can actually read from members of an union, even though you haven't written to them most recently. For an Operation System, it doesn't have to matter whether a user program writes to an union or to a structure. This actually is only an issue of the compiler.

union和struct的另一个重要属性是,它们允许指向它们的指针可以指向其任何成员的类型。因此,以下是有效的:

struct test {
    int a;
    double b;
} * some_test_pointer;

Some_test_pointer可以指向int*或double*。如果将一个test类型的地址转换为int*,它将指向它的第一个成员,实际上是a。工会也是如此。因此,因为联合将始终具有正确的对齐方式,您可以使用联合来使指向某些类型的指针有效:

union a {
    int a;
    double b;
};

这个联合实际上可以指向int型和double型:

union a * v = (union a*)some_int_pointer;
*some_int_pointer = 5;
v->a = 10;
return *some_int_pointer;    

实际上是有效的,正如C99标准所述:

对象的存储值只能由具有以下类型之一的左值表达式访问: 与对象的有效类型兼容的类型 ... 在其成员中包含上述类型之一的聚合或联合类型

编译器不会优化出v->a = 10;因为它可能会影响*some_int_pointer的值(该函数将返回10而不是5)。

是的,struct和union之间的主要区别和你说的一样。 Struct使用其成员的所有内存,union使用最大的成员内存空间。

但所有的区别在于使用内存的需要。 在unix的进程中可以看到联合的最佳使用,在那里我们使用信号。 比如一个进程一次只能作用于一个信号。 所以一般声明是:

union SIGSELECT
{
  SIGNAL_1 signal1;
  SIGNAL_2 signal2;
  .....
};

在这种情况下,进程只使用所有信号中最高的内存。 但如果在这种情况下使用struct,内存使用量将是所有信号的总和。 有很大的不同。

总之,如果您知道一次访问任何一个成员,则应该选择Union。