[\<- 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{ variable declaration; variable declaration; ... } UNION_T; ``` Both examples above are type definitions and do not allocate memory Union Example: ``` typedef union{ 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{ int age; char artist[20]; } ART_INFO; typedef struct{ 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!