summaryrefslogtreecommitdiff
path: root/01-24.md
blob: 2f98b100b3b3e26e1a37b8ff948c850c23db9a60 (plain)
1
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
60
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
[\<- Notes 01/17](01-17.md)

---

# Unions

- A union is a data structure that overlays components in memory
	- Allows one chunk of memory to be interpreted in multiple ways
- The union is used for saving space
	- In situations in which one needs a data object that can be interpreted in a variety of ways

Declaration Outline:

```
union union_t{
	variable declaration;
	variable declaration;
	...
};
```

Alternatively, you can use `typedef`:

```
typedef union union_t{
	variable declaration;
	variable declaration;
	...
} UNION_T;
```

Both examples above are type definitions and do not allocate memory

Union Example:

```
typedef union art_info{
	int age;
	char artist[20];
} ART_INFO;
```

- Defines a Union Type
	- The name of `ART_INFO` is the union tag
	- The identifiers are called members (like in structures)
	- Members can be any valid C data type
	- With this example, `ART_INFO` can be used like int, char, etc.

```
ART_INFO info;
```

- `info` is a variable
- `info` **does not have both components**
	- Amount of memory allocated depends on the largest component in the union
- the member variables are accessed using the dot operator

```
info.age = 2000;
```

or

```
strcpy(info.artist, "Michelangelo");
```

- Member names are local and not known outside the union

- Like structures, unions can be declared as an array of unions:

```
ART_INFO info_array[20];

info_array[0].age = 1000;
```

- Pointers to unions can be declared
	- Like with structures, arrow operator is used to access members for pointers

- Union example in a Structure:

```
typedef union art_info{
	int age;
	char artist[20];
} ART_INFO;

typedef struct art_class{
	char name[20];
	int class;
	ART_INFO info;
} ART_CLASS;

ART_CLASS class_array[4] = 
{{"Mask of Agamemnon", 0, .info.age = 3500},
{"Mona Lisa", 1, .info.artist = "Leonardo da Vinci"},
{"Nok rider and horse", 0, .info.age = 2000},
{"Pieta", 1, .info.artist = "Michelangelo"}};
```

- Be careful not to reference an invalid member in your union!

---

[-> Notes 01/29](01-29.md)