42.md 3.1 KB
Newer Older
W
wizardforcel 已提交
1
# C 联合
W
init  
wizardforcel 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

> 原文: [https://www.programiz.com/c-programming/c-unions](https://www.programiz.com/c-programming/c-unions)

#### 在本教程中,您将学习 C 编程中的联合。 更具体地说,如何创建工会,访问其成员以及了解工会与组织之间的差异。

联合是用户定义的类型,与 C 中的[结构相似,但有一个键差异。 结构分配足够的空间来存储其所有成员,而工会则分配空间来仅存储最大的成员。](/c-programming/c-structures)

* * *

## 如何定义工会?

我们使用`union`关键字定义联合。 这是一个例子:

```c
union car
{
  char name[50];
  int price;
};

```

上面的代码定义了派生类型`union car`

* * *

## 创建并集变量

定义联合后,它将创建用户定义的类型。 但是,没有分配内存。 要为给定的联合类型分配内存并使用它,我们需要创建变量。

这是我们创建联合变量的方法。

```c
union car
{
  char name[50];
  int price;
};

int main()
{
  union car car1, car2, *car3;
  return 0;
}

```

创建并集变量的另一种方法是:

```c
union car
{
  char name[50];
  int price;
} car1, car2, *car3;

```

W
wizardforcel 已提交
60
在这两种情况下,都创建类型为`union car`的并集变量`car1``car2`和联合指针`car3`
W
init  
wizardforcel 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

* * *

### 访问工会成员

我们使用`.`运算符访问工会的成员。 要访问指针变量,我们还使用`->`运算符。

在上面的示例中,

*   要访问`car1``价格`,请使用`car1.price`
*   要使用`car3`访问`价格`,可以使用`(*car3).price``car3->price`

* * *

## 联合与结构之间的区别

让我们以一个例子来说明联合与结构之间的区别:

```c
#include <stdio.h>
union unionJob
{
   //defining a union
   char name[32];
   float salary;
   int workerNo;
} uJob;

struct structJob
{
   char name[32];
   float salary;
   int workerNo;
} sJob;

int main()
{
   printf("size of union = %d bytes", sizeof(uJob));
   printf("\nsize of structure = %d bytes", sizeof(sJob));
   return 0;
} 
```

**输出**

```c
size of union = 32
size of structure = 40

```

**为什么工会和结构变量的大小存在差异?**

W
wizardforcel 已提交
114
这里,`sJob`的大小为 40 个字节,因为
W
init  
wizardforcel 已提交
115 116 117 118 119

*   `name[32]`的大小为 32 个字节
*   `salary`的大小为 4 个字节
*   `workerNo`的大小为 4 个字节

W
wizardforcel 已提交
120
但是,`uJob`的大小为 32 个字节。 这是因为联合变量的大小将始终是其最大元素的大小。 在上面的示例中,其最大元素(`name[32]`)的大小为 32 个字节。
W
init  
wizardforcel 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

使用联合,所有成员共享**相同的内存**

* * *

### 示例:访问工会会员

```c
#include <stdio.h>
union Job {
   float salary;
   int workerNo;
} j;

int main() {
   j.salary = 12.3;

   // when j.workerNo is assigned a value,
   // j.salary will no longer hold 12.3
   j.workerNo = 100;

   printf("Salary = %.1f\n", j.salary);
   printf("Number of workers = %d", j.workerNo);
   return 0;
}
```

**Output**

```c
Salary = 0.0
Number of workers = 100

```

* * *

要了解在哪里使用联合,请访问[为什么我们需要 C 联合?](https://stackoverflow.com/questions/252552/why-do-we-need-c-unions)